Encapsulation in Java : Free Java Tutorials

 Encapsulation is the process of binding data variables and the corresponding methods into a single unit. Every class in Java is an example of encapsulated class. It brings high security and reliability to an application.

Consider an example of a class named Teacher which contains data variables related to teaching profession and methods which represent the behavior of a teacher.

This class follows encapsulation since data and behavior are bound together in the class.If any component follows Data Hiding and Abstraction, then we can say that it is an encapsulated component.

Encapsulation = Data Hiding + Abstraction

Example of Encapsulated Class

public class Account
{
	// Account balance is kept private for data hiding purpose
	private double balance;
	
	public double getCurrentBalance()
	{
		// perform user validation and then return account balance
		return balance;
	}
	
	public void setCurrentBalance(double new_balance)
	{
		// perform user validation and then set account balance
		this.balance = new_balance;
	}
}

In the above example, the class Account has data variable named balance, which is private for data hiding purpose.

Also, the methods setCurrentBalance() and getCurrentBalance() allow abstraction to take part.

Suppose, bank’s User Interface has two buttons named ‘check balance’ and ‘update balance’.

Clicking these two buttons will directly call getCurrentBalance() and setCurrentBalance() methods.

This way, we can change business logic inside these two methods and it will not have any effect on the user interface.

This combination of data hiding and abstraction makes the class Account encapsulated.


Advantages and Disadvantages of Encapsulation in Java

Advantages

  1. We can achieve tight security.
  2. Ease of enhancement increases.
  3. Application maintainability improves.

Disadvantages

  1. Too much encapsulation increases the length of the code and slows down execution and hence affects the overall performance of the system.

Tightly Encapsulated Class

A class follows tight encapsulation if and only if each and every data variable of that class is private.

If the class contains at least one data variable which is not declared as private, then that class is not a tightly encapsulated class.It is not necessary to check whether the class contains public getter and setter methods or not.

This is all about Encapsulation in Java. Hope you find this tutorial helpful.

Leave a Comment

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