Encapsulation in Java



A mechanism that associates the code and the data it manipulates into a single unit and keeps them safe from external interference and misuse.

Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield. In this, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.

Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.

Example 1:

Output :


Example 2:

Output :

Enter employee Name: aimtocode
Enter employee SSN: 921915
Enter employee Age: 22