Definition : Encapsulation in java is a process of wrapping code i.e data (Variables) and and processes performed on that data i.e methods together into a single unit called class. For example capsule i.e. mixed of several medicines.

 

  • In encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
  • We can also use getter and setter methods to get and set data in it.
  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
  • Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.

 

Example :

 

 public class Encapsulation {

private      String name;

private      int rollno;

 

String getName() {

return name;

}

void setName(String name) {

this.name = name;

}

int getRollno() {

return rollno;

}

void setRollno(int rollno) {

this.rollno = rollno;

}

public static void main (String[] args){

Encapsulation e = new Encapsulation();

e.setName(“nandini”);

e.setRollno(100);

System.out.println(e.getName());

System.out.println(e.getRollno());

}

}

—————————————————————————————————————————————-

   Output : nandini

                      100

—————————————————————————————————————————————-

Leave a Reply