Encapsulation In Java

In the object-oriented world, we have pillars of programming. One of them is Encapsulation the other three are Inheritance, polymorphism, and abstraction.

Here's the article which will explain, What, Why, and How of Encapsulation, and the other three are yet to be released one by one. So let’s get started with encapsulation.


According to most of the resources, encapsulation means hiding the data members (variables and methods) within the class or a mechanism of wrapping/hiding a code and the variables/methods together as a unit.

In this, we will come across the entire concept of what encapsulation means, why to use encapsulation and how to achieve encapsulation in the programming world.

Data Hiding Vs Encapsulation

When encapsulation is implemented, only the variables inside the class can access it.

Therefore it's known as data hiding. But encapsulation and data hiding both are different from each other.

Data Hiding means protecting the members of a class from unauthorized/illegal access.

Encapsulation automatically achieves the concept of data hiding by providing security to data by making the variables as private.

As it is difficult to understand encapsulation through definitions we will learn in depth about this through some code examples,

package Encapsulation;  
//Use of POJO (Plain Old Java Object) class 
public class Employee {  
 //Member Variables 
    String name;  
 int age;  
    String address;  
 void code() {}  
 void role() {}  
 void employer() {}  

Here the common behavior and characteristics of an employee are enclosed in a single unit, the Employee.java class. This is a process of encapsulation.

An Employee object exposes its behavior and characteristics to the outside world.

Employee emp = new