Skip to content
APPCITORThe Tech Blog
Esc

Java OOP – Encapsulation

August 16, 2020 2 min read

Java OOP – Encapsulation

Encapsulation is binding of object state(fields) and behavior(methods) together. The idea behind the encapsulation is to hide the implementation details from the user.

  • In previous articles we discussed about Inheritance and Polymorphism. You can refer those concepts before going to the encapsulation.

Let’s go back to the topic Encapsulation.

Real world Example for encapsulation is:

Let’s take a capsule consist of medicine. The medicine you should take is inside the capsule and you do not know what medicine is inside the capsule. But from the capsule you can cure your illness. No need to know what is inside the capsule.

Like that we encapsulate or hide data from the user as use doesn’t need to know about those data.

Let’s see an example.

First we should make the instance variables private so that they cannot be accessed directly from outside the class. These fields can be accessed via public methods only. You can only set and get values of these variables through the methods of the class.

Then create the getter and setter methods in the class to set and get the values of the fields. Let’s see how we can access data.

Output:

Advantages of Encapsulation:

  • It improves maintainability and flexibility and re-usability.
  • The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class).
  • User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.

Fully Encapsulated classes are also known as Java Bean Classes.

Let me know if you guys have any doubt on today’s topic.

See you from the next article on the topic “Abstraction” which is the next OOP concept.

Thank you.

Share this article

Keep reading