encap - Encapsulation in Java

Encapsulation in Java

Posted on

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

encap - Encapsulation in Java

 

  • In encapsulation, the variables or knowledge of a category is hidden from some other class and will be accessed solely by any member operate of personal class by which they’re declared.
  • We will additionally use getter and setter strategies to get and set knowledge in it.
  • As in encapsulation, the information in a category is hidden from different lessons, so additionally it is referred to as data-hiding.
  • Encapsulation will be achieved by: Declaring all of the variables within the class as personal and writing public strategies within the class to set and get the values of variables.

 

Instance :

 

 public class Encapsulation {

personal      String title;

personal      int rollno;

 

String getName() {

return title;

}

void setName(String title) {

this.title = title;

}

int getRollno() {

return rollno;

}

void setRollno(int rollno) {

this.rollno = rollno;

}

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

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