Encapsulation in Java – OOPS Concepts

In this post we’ll see the usage of OOPS concept Encapsulation in Java.

What is encapsulation

Encapsulation is one of the four fundamental principles of Object Oriented Programming along with inheritance, polymorphism and abstraction.
Encapsulation is the process of keeping the data and the code that manipulates that data together as a unit. That way data is protected from any intentional or accidental modification by any outside entity. Since encapsulation is more about protecting data from being accessed by other classes so encapsulation is also referred as data hiding.

Encapsulation in Java

Encapsulation in Java is achieved through a Java class and the access modifiers. A properly encapsulated class shall have all its fields marked as private (so can’t be accessed by any other class) and the methods with in that class defining how data can be used and accessed.

encapsulation in Java

Java example for encapsulation

Consider a Java class Voter with name, age and address fields.

If you notice setAge() method has a condition that age should not be less than 18, if it is then exception is thrown. Consider the scenario where data fields are not marked as private, from any class following code could be written (accidentally or intentionally)

making a 5 year old eligible to vote.

But Voter class follows encapsulation so data is only accessed through the methods of the class (setters and getters) where the required verification is done. With that any such attempt will not be successful and exception will be thrown.

Only when the values are proper, a voter slip can be printed.


Advantages of encapsulation in Java

  1. Since data and the code that works on that data is kept in the same Java class so encapsulation also makes the code more manageable and easy to maintain.
  2. In Java encapsulation is achieved by restricting access to the class fields that enhances security.
  3. Encapsulation also gives you flexibility about the access of the fields by making them read only, write only or both. In the example Voter class we can remove the getter methods making all the fields write only. In that case fields can only be read by using printSlip() method.

That’s all for the topic Encapsulation in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.