1. What Is Encapsulation?

It’s quite difficult to understand the concept of encapsulation from a definition. So let’s understand what encapsulation is by looking at some code examples.

Basically, there are two forms of encapsulation in OOP.

First, encapsulation is a technique that packages related data and behaviors into a single unit. Let’s see an example:

class Person {
	String name;
	int age;
	
	void talk() {
	}
	
	void think() {
	}
	
	void work() {
	}
	
	void play() {
	}
}
Here, the common characteristics and behaviors of a person are packaged into a single unit: the Personclass. This is the process of encapsulation.

The Person class is an encapsulation unit. A Person object exposes its attributes and behaviors to the outside world:

Person you = new Person();
you.name = "John";
you.work();
Here, encapsulation hides implementation details of the Person class from other objects.

Likewise, creating an interface is also the process of encapsulation:

interface Human {
	void eat();
	void talk();
	void think();
}
Again, in terms of encapsulation, this interface groups the essential behaviors of human-being in a single unit.

Second, encapsulation is a technique for protecting data from misuse by the outside world, which is referred as ‘information hiding’ or ‘data hiding’.



In Java, the access modifier privateis used to protect data and behaviors from outside. Let’s modify the Person class above to prevent the attributes name and age from being modified by other objects:

class Person {
	private String name;
	private int age;
}
Here, the fields age and name can be only changed within the Person class. If someone attempts to make a change like this:

Person p = new Person();
p.name = "Tom";	// ERROR!
The code won’t compile because the field name is marked as private.

But what if we want the other objects to be able to read the name and age? In this case, we provide methods whose name in the form of getXXX() - so called getters in Java. Hence we add two getters to the Person class:

class Person {
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	
	public String getAge() {
		return age;
	}
}
This is the process of hiding information. The other objects cannot access the data directly. Instead, they have to invoke the getters which are designed to protect the data from misuse or unwanted changes.

What if we want the outside world to be able to modify our data in a safety manner? In this case, we can provide methods in the pattern of setXXX() - the so called setters in Java. For example, creating a setter for the field name:

public void setName(String name) {
	if (name == null || name.equals("")) {
		throw new IllegalArgumentException("name cannot be null or empty!");
	}
	
	this.name = name;
}
Here, someone can change the name of a Person object via this setter method, but he cannot set an empty or null name - as the setter will throw an exception if doing so. This protects data from misuse or malicious changes. For example:

Person p = new Person();

p.setName("");	// ERROR: IllegalArgumentException will be thrown

p.setName("Tom");	// OK, legal
Likewise, we can implement a setter for the age attribute that allows the caller to set age in a valid range. For example:

public void setAge(int age) {
	if (age < 18 || age > 55) {
		throw IllegalArgumentException("Age must be from 18 to 55");
	}
	this.age = age;
}
So far you’ve got an understanding about what encapsulation is in OOP and how it is implemented in Java. In short, encapsulation is a technique for hiding implementation details and restricting access for the outside world.

 

2. Why Is Encapsulation?

It’s because encapsulation has a number of advantages that increase the reusability, flexibility and maintainability of the code.

  • Flexibility: It’s more flexible and easy to change the encapsulated code with new requirements. For example, if the requirement for setting the age of a person changes, we can easily update the logic in the setter method setAge().  

  • Reusability: Encapsulated code can be reused throughout the application or across multiple applications. For example, the Person class can be reused whenever such type of object is required.  

  • Maintainability: Application ode is encapsulated in separate units (classes, interfaces, methods, setters, getters, etc) so it’s easy to change or update a part of the application without affecting other parts, which reduces the time of maintenance.
 

3. How Is Encapsulation Done in Java?

As you can see in the above examples, encapsulation is implemented in Java using interfaces, classes, access modifiers, setters and getters.

A class or an interface encapsulates essential features of an object.

Access modifiers (private, public, protected) restrict access to data at different levels.

Setters and getters prevent data from misuse or unwanted changes from other objects.

That’s all for encapsulation topic today. Right now, take a pencil and a paper to take note what you have learned.

 

4. Encapsulation vs. Abstraction

So far you got a proper understanding about abstraction and encapsulation in Object-Oriented Programming with Java. To summary:

  • Abstraction is the process of modeling real things in the real word into programming language. In Java, the process of abstraction is done using interfaces, classes, abstract classes, fields, methods and variables. Everything is an abstraction.
  • Encapsulation is the process of hiding information details and protecting data and behavior of an object from misuse by other objects. In Java, encapsulation is done using access modifiers (public, protected, private) with classes, interfaces, setters, getters.
So, what are the commons and differences between abstraction and encapsulation?

Many programmers have been wondering about this.

If you are wondering about this too, here’s my answer:

Hey, there are NO commons and differences between abstraction and encapsulation. Why? It’s because they are not comparable.

They are about different things, so we cannot compare them.

As I told you in the article What is Abstraction in Java - the WHY and the Truth, abstraction is the fundamental concept on which other things rely on such as encapsulation, inheritance and polymorphism. In other words, if there is no abstraction, encapsulation would not exist.

Encapsulation is done based on abstraction. Imagine you are building a house. The house is made by bricks. Abstraction is the bricks and encapsulation is the house. Got it?

That’s all about abstraction and encapsulation today. You know, it took me years to really understand and figure out this mater. Now you got it in just some minutes.

 

Related Tutorials:

  

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#9Sebastian2022-01-05 09:40
Thank you bro, my read practice to day about java I got it, and English practice
Quote
#8Mangosit2022-01-03 14:29
It took me more that 5 years to understand this concept. you made me clear today!
Fantastic explanation
Quote
#7Chandra Shekhar Pand2021-03-16 02:58
thanks and simply woowwww woowwwwwoowwww
Quote
#6deep9862020-07-06 06:06
Nice article written by Nam. Thank you for sharing it. Encapsulation in Java
Quote
#5ALOTAIBI mohammed2020-02-24 22:06
Great
Yes , it is very clear that it took you years to really understand and figure out this mater.
Quote