Encapsulation in Java | Java Tutorial

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.



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

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.


2 thoughts on “Encapsulation in Java | Java Tutorial”

  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