Java Encapsulation

In this tutorial, you will learn about encapsulation and data hiding in Java with the help of examples.

Java Encapsulation

Encapsulation is one of the key features of object-oriented programing. Encapsulation refers to the bundling of fields and methods inside a single class.

Bundling similar fields and methods inside a class together also help in data hiding.


Encapsulating fields and Methods

In general, encapsulation is a process of wrapping similar code in one place.

In Java, we can bundle fields and methods that operate together inside a single class. For example,

class Rectangle {
   int length;
   int breadth;
   public void getArea() {}
}

In the above program, the method getArea() calculates the area of a rectangle. To calculate the area, it needs length and breadth. Hence, the data fields length, breadth and the method getArea() are kept together in the Rectangle class.


Java Data Hiding

Data hiding is a way of restricting the access of our data members by hiding the implementation details.

Encapsulation also provides a way for data hiding.

Data hiding can be achieved with the help of access modifiers. In Java, there are four access modifiers:

  • public - visible from anywhere
  • private - visible from only within the class
  • protected - visible within the package, and among its subclasses
  • default - visible within the package

To learn more visit Java Access Modifiers.

Example 1: Data Hiding Using private

class Person {
   private int age;

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }
}

class Main {
   public static void main(String[] args) {
      Person p1 = new Person();
      p1.setAge(24);
      System.out.println("My age is " + p1.getAge());
   }
}

Output

My age is 24

In the above example, we have a private field age. Since it is private, it cannot be accessed from outside the class. In order to access age, we have used public methods getAge() and setAge(). These methods are called getter and setter methods.

If we try to access the age field from the Main class, we will get an error.

p1.age = 24;     // error: age has private access in Person

Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding.


Example 2: Data Hiding using protected

class Person {
 protected String profession;

 protected void displayInfo() {
   System.out.println("I am a " + profession);
 }
}

class Teacher extends Person {
   public static void main(String[] args) {
      Teacher t1 = new Teacher();
      t1.profession = "teacher";
      t1.displayInfo();
   }

}

Output

I am a teacher

In the above program, we have created a class Person which includes a protected field profession and a protected method displayInfo().

We have accessed these members from the Teacher class (which is a subclass of Person).


Why Encapsulation?

  • In Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read.
  • It helps to control the modification of our data fields. Consider a situation where we want the age field in a class to be non-negative. Here we can make age private and can apply logic inside the method setAge(). For example,
class Person {
   private int age;

   public void setAge(int age) {
     if (age >= 0) {
        this.age = age;
     }
   }
}
  • The getter and setter methods provide read-only or write-only access to our class fields. For example,
getName()   // provides read-only access
setName()   // provides write-only access
  • It helps to decouple components of a system. These decoupled components can be developed, tested and debugged independently and concurrently. And, any changes in a particular component do not have any effect on other components.

Data Hiding Vs. Encapsulation

People often consider encapsulation as data hiding, but that’s not entirely true.

Encapsulation refers to the bundling of related fields and methods together. This allows us to achieve data hiding. Encapsulation in itself is not data hiding.