Encapsulation in Java

Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.

Encapsulation In Java

We will see detailed explanation with some example programs about Encapsulation in the post related to Encapsulation.

Let’s see how can we implement encapsulation. Set the instance variables private so that these private variables cannot be accessed directly by other classes. Set getter and setter methods of the class as public so that we can set and get the values of the fields.

Let’s see a sample program.

 

Output:

In the above example, you can find all the data member (variables) are declared as private. If the data member is private it means it can only be accessed within the same class. No other class can access these private variables of other class. To access these private variables from other classes, we used public getter and setter methods such as getAge(), getName(), setAge(), setName(). So, the data can be accessed by public methods when we can set the variables private and hide their implementation from other classes. This way we call encapsulation as data hiding.

Must Read: Java Tutorial

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

2 thoughts on “Encapsulation in Java”

  1. Perfect explanation brother. Just matched my grasping level

    • Thanks for your kind words.

Leave a Comment

Share via
Copy link
Powered by Social Snap