Encapsulation

  • Eclipse: Oxygen
  • Java: 1.8

In Java, Encapsulation is the process of binding the class members (variables and methods) into a single unit. It protects the data of class to be accessed from outside the class.

In Encapsulation, we hide the implementation details from the outer class and provided them the controlled access to the class.

Encapsulation can be achieved by declaring the instance variables as private. However, we can access the private variable through the getter and setter method. setter method used to update ( void setAge() ) and getter method is used to read (int getAge() ) the value  of private variable.

In the following example, we demonstrate how to implement encapsulation and benefits of encapsulation.

Person class has some public properties and these properties can be accessed and modified from the outside classes.

To implement the implement the encapsulation concept, we need to convert the public properties into private and to get the default value of these variables we need getter method.

Output:

John

25

Male

We will write a setter method to modify the value.

We will modify the value of private members from a different class using setter method.

Output:

John

25

Male

We can apply some restrictions and rules inside the setter method.

Now if we provide the age value outside the limit, then the default value will be provided to the variable.

Output:

John

0

Male

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu