Java Encapsulation

encapsulation in java

There are 4 core concepts in OOP: encapsulation, inheritance, polymorphism, and abstraction. Java Encapsulation is one of the four fundamental OOP concepts.

The idea behind encapsulation is to ensure that implementation details are not visible to users. The variables of one class will be hidden from the other classes, accessible only through the methods of the current class.  Therefore, it is also known as data hiding.


To achieve encapsulation in Java:

* declare the class’ variables as private.

* provide public setter and getter methods to modify and view the variables’ values.


Example :

Following is an example that demonstrates how to achieve Encapsulation in Java :
/* File name : EncapTest.java */
public class EncapTest {
   private String name, 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;
   }
}

Benefits of Encapsulation:

i) Control of the way data is accessed or modified.

ii) More flexible and easily changed code.

iii) Ability to change one part of the code without affecting other parts.


Spread the love

Leave a Comment

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