What is Encapsulation?

1 answers

Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:

  • The internal state of every object is protected by hiding its attributes.
  • It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
  • It improves modularity by preventing objects to interact with each other, in an undesired way.

A sample class Student which has attributes Id and Name is shown as an example for encapsulation.

public class Student{ 

private int id;

private String name; 

public void setId(int id){

this.id = id;

}

public void setName(String name){

this.name = name;

}

public int getId(){

return this.id;

}

public String getName(){

return this.name;

}

public static void main(String args[]){ 

Student student=new Student(); 

student.setId(``1034``);

student.setName("David Smith");

System.out.println("Student id "+ student.getId());

System.out.println("Student name "+ student.getName());

} 

}
shilpigupta22 shilpigupta22 [Author] 2 months ago votes 0