Encapsulation in Java

In this tutorial, we will learn about Encapsulation in Java.

Encapsulation is one of the four fundamental Object Oriented Programming (OOP’s) concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation in java is a process of wrapping code and data together into a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
In Java, a Class is a best example of encapsulation. We can create a fully encapsulated class in java by making all the data members of the class private and providing public setter and getter methods to modify and view the attribute values.

Advantages of Encapsulation:

1) Data Hiding:

The users of a class do not know how the class stores its data. The things are happening behind the scene. A class may change the data type of a field and the user need not bother about it. The users would only be knowing that to update a field call setter method and to read value of an attribute call getter method.

2) Flexibility:

The fields can be made read-only or write-only based on the requirement. If we want to make fields read only then we have to provide getter methods only for the fields.

3) A class has control over the fields and the data stored in the fields.

Example of Encapsulation:

Now we know that for Encapsulation, the variables of a class must be private. Let’s create an Employee.java class with all the variables in the class as private.

Employee.java:

Let’s create an EncapsulationDemo.java class.

EncapsulationDemo.java:

Let’s run the EncapsulationDemo.java class and check the output.

Output:

In the above class, all the 3 data members are private and can only be accessed using setter and getter methods.
The fields name, age and address are made hidden using Encapsulation.

Other tutorials:

Related posts

Leave a Comment