Encapsulation In Java

Mukta Sharma
2 min readJun 4, 2021
Image Credit: Sitesbay/Google

What is Encapsulation?

Hi there, in today’s article, we will discuss another important feature of OOP (Object Oriented Programming) language called — “Encapsulation”. As the above diagram displays, when variables or methods are bound together into a single unit, is called “Encapsulation”.

Encapsulation is also known as “Data Hiding”.

In simple words, Encapsulation is a process of wrapping the data or the variables and the methods together as a single unit that can not be accessed outside the class.

How do we achieve Encapsulation?

There are 2 ways to achieve Encapsulation:

  1. By declaring all the variables of a class as private.
  2. By creating public getter and public setter methods to modify and view the values of the variables.

Let us implement encapsulation with the help of an example.

Example:

class Student
{
//private data variables
private int student_id;

//created setter method
public void setStudentId(int studid1)
{
student_id=studid1;
}

//created getter method
public int getStudentId()
{
return student_id;
}

}

In the above example, studentid can be used only in Student class.
Here, we are adding an access specifier private with a variable studentid, this concept is called Data Hiding which means studentid can not be accessed by other classes directly. The whole process is called “Encapsulation”.

Advantages of Encapsulation:

  1. Improves maintainability of code
  2. Reusability

I hope, this will help you in understanding Encapsulation. You can start writing with some basic code to implement Encapsulation for practice purposes.

Please feel free to share your inputs. Let's learn, grow and improve together. Thank you for reading it!

--

--

Mukta Sharma

Hi,I write on software testing( Manual testing,Automation,API,Mobile,InterviewQ&A etc.). My YT link :https://www.youtube.com/channel/UCppaYb_VotTvHxb6b3pE_5Q