OOP Concepts: Encapsulation

A practical guide with Java

Manusha Priyanjalee
3 min readJan 1, 2020
Photo by Anshu A on Unsplash

Encapsulation is one of the four pillars of object-oriented programming. It describes the idea of wrapping of data (variables) and code acting on the data (methods) together as one single unit.

Consider a program like this.

A program without using the encapsulation concept

In this program the instance variables are exposed. Exposed means you can reach the variable with the dot operator, as in: r.marks = 80. Think about the idea of anyone using the reference variable to make a direct change to the marks instance variable like: r.marks = -10. This can destroy your whole effort because you are leaving your data out there for anyone to see and change.

To avoid such vulnerabilities we need to create setter and getter methods for all the instance variables. So we can deny marks variable having unacceptable values assigned for it. For example marks cannot be negative.

For this we need private and public access modifiers. Make the instance variables private and setter and getter methods public. But for this situation we also need to include some conditions in setter methods to avoid instance variables being assigned unacceptable values.

Record class using encapsulation concept
Class with the main method

Now no one can give an unacceptable value for both marks and rank variables. The output is shown below.

Output of the above program

Now you may have the question that some setter methods simply set the value without checking any condition. Let’s take setStudent() method. It simply set the name of the student. We can do the same with the reference variable and dot operation if we make the student variable public.

But what if you had to change the code later and many other people are already using your Record class with public instance variable student. Everyone’s code has to change according to the changes you are adding. But if you have created a setter method for it then you can change your code anytime without breaking anyone else’s code. This is the main point of using setter and getter methods.

I hope this article helped you to get a clear understanding of encapsulation.

Happy Coding!

--

--