Encapsulation is the process of wrapping of data i.e. variables and code that acts on data i.e. methods in a single unit.
In encapsulation the variables are kept private and can only be accessed by the methods. Now here the data members are kept hidden from other classes therefore it is known as data hiding. The private data can be accessed by using getter and setter methods.
1. It allows us to make any field read-only or write-only. For this we have to use only getter and setter.
2. We will have control over the stored value in a field.
Here is a very simple example for encapsulation.
Above class is class made for an employee. We have two private variables name and id. There are methods for getter and setter so that variables can be accessed from outside the class. Below class is uses Employee class and sets name and id for an employee. After that it is getting the data to display using getter methods.