encap 2 - Encapsulation in Java

Encapsulation in Java

Posted on

Definition : Encapsulation in java is a means of wrapping code i.e knowledge (Variables) and and processes carried out on that knowledge i.e strategies collectively right into a single unit known as class. For instance capsule i.e. blended of a number of medicines.

 

  • In encapsulation, the variables or knowledge of a category is hidden from another class and may be accessed solely by any member operate of personal class through which they’re declared.
  • We are able to additionally use getter and setter strategies to get and set knowledge in it.
  • As in encapsulation, the info in a category is hidden from different courses, so it’s also referred to as data-hiding.
  • Encapsulation may be achieved by: Declaring all of the variables within the class as non-public and writing public strategies within the class to set and get the values of variables.

 

Instance :

 

 public class Encapsulation {

non-public      String identify;

non-public      int rollno;

 

String getName() {

return identify;

}

void setName(String identify) {

this.identify = identify;

}

int getRollno() {

return rollno;

}

void setRollno(int rollno) {

this.rollno = rollno;

}

public static void predominant (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

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