Encapsulation In Java With Example

May 09, 2022
xblog Encapsulation


Encapsulation is not a new concept for Java developers. It is among the four fundamental concepts of object-oriented programming. Encapsulation in Java allows developers to conceal the data and the code together in a single unit. There are various benefits and ease provided by encapsulation in Java that we will be discussing in this article.

Encapsulation in Java

Encapsulation is an object-oriented programming implementation technique where the related data members are stored in a single unit (class) and member functions are used for indirect access from the user side. This provides a clean and well-managed code that can be easily expanded and has increased security. Encapsulation is considered one of the most important concepts of object-oriented programming.

explore new Java roles

The data cannot be accessed directly. The only way to access the data is provided by the functions (that are combined along with the data). These member functions or methods are termed as setters and getters in Java (these will be discussed later). If you want to read a data item in an object (an instance of the class), you can call a member function in the object. The methods read the item as well as return the value.

To achieve encapsulation in Java, you must fulfill the following rules:

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to access, modify and view the data stored in the variables.

Objects and classes in Java

Before we dive into encapsulation in Java, let’s revisit some of the basic object-oriented programming (OOP) concepts starting with two main things: objects and classes.

Objects are the identifiable entities with limited features and behavior of a class in execution with the actual data values.

Classes are the collection of objects with common properties and relationships using the same data members and member functions defined.

How does encapsulation work?

Consider a simple analogy for understanding encapsulation. There are usually various departments in a school such as academics, administration, finance, logistics, etc. Each department has its personnel to manage the data and operations. If an employee in the academic department wants to get some information from the finance department. He would not be allowed to himself go through the data files. Rather he will have to issue a request for the required information and some employee from the finance department will provide that information.

This practice is a norm in all organizations as it ensures that the data is accessed accurately and that it is safe from unauthorized access. This is the same concept as Encapsulation in Java and other OOP languages.

To understand how encapsulation works in Java, consider the following code. A class my_account is made with show data and credit amount methods:

1. class myAccount {
2.     private int account_ID;
3.     private int current_balance;
5.     public void show Data() {
6.         //code to show data
7.     }
9.     public void credit_Amount(int amount) {
10.        if (amount < 0) {
11.            //present an error
12.        } else
13.            current_balance = current_balance + amount;
14.     }
15.  }

Now, suppose you want to change the amount into your account. You can attempt to manipulate the code from the class directly by assigning an amount to the variable like this:

1. Class newClass{
2. myAccount obj1 = new myAccount();
3. obj1.current_balance = 100;
4. }

This will not be allowed as the current_balace variable is set as “private”, it can only be accessed with the setter method defined in its own class.  If a variable is private, it means it can only be accessed within the same class. No outside class has access to private data member or variable of other class. Thus, your data will never be exposed externally. The complete code is considered like a capsule, and you can only communicate through a specific channel (methods). That also explains the term “encapsulation”.  This also provides better management by the grouping of related data.

Data hiding

Encapsulation hides the variables to protect the data and the behavior of the object. The variables of a class will be inaccessible as well as hidden from all the other classes, this is why encapsulation is also referred to as data hiding.

The data is hidden, so it is kept safe from accidental alteration as well as unauthorized access. It not only hides the data but the implementation details are also kept hidden from the users. This makes the application even more secure and safe from unauthorized modification in the code.

Getters and setters in Java

As we cannot directly access or change the data in a variable, there must be a way to do that or how would a developer be able to access data. For that, we have Getter and Setters.

Getter and Setter are the two conventional methods used in Java to retrieve and update the values of a variable through encapsulation. They are used to create, modify, delete and view the data stored in variables indirectly. The setter method is used for updating (setting) the values and the getter method is used for reading or retrieving (getting) the values from the variables. They are also referred to as accessors and matadors.

The following code demonstrate the use of getter and setter methods to access values in encapsulation:

1. class myAccount{
2. private int account_ID;
3. private int current_balance;
4.     // getter method
5.                 public int getCurrentBalance() {
6.         return this.current_balance;
7.      }
8.     // setter method
9.                 public void setAccount_ID(int id) {
10.         this.account_ID = id;
11.     }
12.  }

In this example, getCurrentBalance() is a getter method that returns the value from the variable current_balance() and setNumber() method is setter method used to set or modify the value for variable account_ID.

Difference between abstraction and encapsulation

Encapsulation is often misunderstood with abstraction but there is a subtle difference between both of them. Encapsulation is a way to implement data abstraction. Data abstraction focuses on the observable behavior of an object whereas encapsulation focuses upon the implementation. encapsulation is more towards “How” to achieve a functionality Whereas abstraction is more towards “What” a class can do.

Abstraction hides the complexity and detailing to just allows us the required features. For instance, while sending a text message, we just type the text and send it. We are not concerned with how the message will be delivered or what are the internal processes that perform the delivery. Abstraction can only be achieved using Abstract Class and Abstract Method in Java.

Abstract Class is a class that is declared with the “abstract” keyword. It can have abstract methods as well as concrete methods but a normal class cannot have abstract methods. Abstract Methods are the methods without a body. They can only be declared in an abstract class. The abstract method can never be final because the abstract class must implement all the abstract methods.

What if encapsulation is not used?

Consider the following Java code demonstration:

1. class myAccount {
2.     public int account_ID;
3.     public int current_balance;
5.     public void show Data() {
7.      }
9.     public void credit_Amount(int amount) {
10.        if (amount < 0) {
11.        } else
12.            current_balance = current_balance + amount;
13.     }
14.  }

Now, there is no encapsulation as all the variables are declared as public and there are no getters or setters to indirectly access the data. If you want to change the value of a variable it can be directly done like this:

1.     public static void main (String [] args)
2.     {
3.         myAccount obj1 = new myAccount();
4.         obj1.current_balance = -5; // value directly got changed!!
5.     }

This is possible but this approach will break your code as everyone can access and modify the variables and despite the condition in the setter that amount cannot be less than zero, the condition can be easily bypassed by setting the values directly.

Now the question is, what changes can be made in the class in such a way that lets you handle the issues that come up when anyone attempts to change the data as now everyone can change the values now.

See Also: Understanding Java Service Loader

To resolve this issue, the only way is to go back and protect the size variable with a private access modifier but doing so will now break everyone else code that would be implemented with your code. This makes it evident that leaving encapsulation will significantly affect the stability, extensibility and security of your code.

Wrapping it up

We have discussed encapsulation in Java along with some basic examples. Encapsulation is one of the strongest features of OOP. It offers you the ability to make changes and extend your code while maintaining security. The set of accessible methods (setter and getter) that are made available for accessing the variables helps in hiding implementation details. The maintainability, flexibility, and extensibility are only possible due to encapsulation and you cannot achieve it in any other way.

new Java jobs



Candidate signup

Create a free profile and find your next great opportunity.


Employer signup

Sign up and find a perfect match for your team.


How it works

Xperti vets skilled professionals with its unique talent-matching process.


Join our community

Connect and engage with technology enthusiasts.