Encapsulation In Java

Encapsulation is among the four essential OOP concepts. Another three are inheritance, polymorphism, and abstract.

Encapsulation in Coffee is a mechanics of rolling the information (variables) and signal performing on the information (procedures) collectively as as solitary component. In encapsulation the variants of a type may be concealed from other groups, and may be obtained only through the processes of the present group, so it’s also called information hiding.

To reach encapsulation in Java

State the variables of a type as private.

Supply community setter and getter methods to change and see the variants beliefs.


Below provided is an illustration that shows the best way to realize Encapsulation in Java:

/* File name : EncapTest.java */
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;

   public String getName(){
      return name;

   public String getIdNum(){
      return idNum;

   public void setAge( int newAge){
      age = newAge;

   public void setName(String newName){
      name = newName;

   public void setIdNum( String newId){
      idNum = newId;

The community setXXX() and getXXX() methods will be the entry points of the instance parameters of the EncapTest group. Generally, these systems are known as getters and setters. So any course that needs to get the variants should get them by means of these getters and setters.

/* File name : RunEncap.java */
public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

The variants of the EncapTest group may be obtained as below::

Advantages of Encapsulation:

The subjects of a type may be made read only or create-only.

A group may have complete control over what's saved in its areas.

The consumers of a group have no idea the way the group save its information. A group may alter the data type of a subject and consumers of the group need not alter any of the signal.

Leave a Reply

Your email address will not be published. Required fields are marked *