logo

Java Encapsulation


Show

Encapsulation is one of the four primary OOP ideas. The other three are legacy, polymorphism, and abstraction.

Encapsulation in Java is an apparatus of packaging the statistics (variables) and code performing on the facts (methods) collectively as a lone unit. In encapsulation, the changeable of a group will be concealed from other groups, and can be contacted only during the techniques of their existing class. Consequently, it is also recognized as facts hiding.

To attain encapsulation in Java:

  • State the unevenness of a group as personal.
  • Offer community setter and getter techniques to adapt and vision the changeable values.

Example

Following is an example that demonstrates how to achieve 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() techniques are the admission ends of the case changeable of the EncapTest class. Usually, these techniques are submitted as getters and setters. Consequently, any class that desires to admission the changeable should admission them during these getters and setters.

The patchy of the EncapTest class can be admitted with the subsequent program

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

   public static void main(String args[]) {
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

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

This will produce the following result:

Output

Name : James Age : 20

Benefits of Encapsulation

  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.