Encapsulation in Java

Yogeshwar
3 min readFeb 22, 2021

--

In the previous article, we have discussed an introduction to OOP, in this article we will dive deep into OOP principles one by one.

Guys keep one thing in mind, without OOP your Java interview is incomplete. So learn these concepts clearly.

Below is the list of OOP principles.

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

First, we will see Encapsulation in detail.

Encapsulation in Java looks very intimidating as a concept at first. Do not worry, we will take it down easily by breaking it down into simpler topics.

What is Encapsulation?

Encapsulation is the process of creating a class by binding variable and its methods as one unit and access those variables only through these methods.

It is the process of creating a class by hiding internal data from outside the world and access it only through publically exposed methods.

Why Encapsulation?

By developing encapsulation we are hiding object data from the outside world. By developing encapsulation we will validate data before storing/setting it to the variable.

How to develop Encapsulation?

In Java, Encapsulation can be developed by following way,

  1. Declare all variables as private.
  2. By defining pairs of public setter & getter methods.

Now, you are getting a question in your mind by using the above way how we can achieve Encapsulation, the answer is

We declare all variables as private so that they can not be accessed directly from outside class.

We define a pair of public setter & getter methods for each variable so that the same private variable can be accessed outside the class directly. We can also validate the data before storing it in a variable.

By developing Encapsulation, We will achieve security to object data.

The Java Bean class is an example of a fully encapsulated class.

By providing only a setter or getter method, you can make the class read-only or write-only. It provides you control over data.

Consider an example, if you want to store a value in a variable that is greater than 18 then you can write this logic in the setter method.

Fully encapsulated class
Encapsulation with data validation
Setting and Getting values from Employee object via setter and getter method.
Advantages of Encapsulation

So this is all about Encapsulation, in the next article, we will see each Inheritance with examples in detail.

Keep in touch, Sharing is Caring!

Thank you…

--

--

Yogeshwar
Yogeshwar

Written by Yogeshwar

Hi, I am Yogeshwar. I am a Software developer by Profession and I am here to share knowledge with you guys.