Java - Encapsulation

What is Encapsulation in Java?

Encapsulation is process of wrapping code and data together into a single unit.

We can create fully encapsulated class by making the entire data member will be private and create getter, setter method to access that data member.

POJO class is the best example of fully encapsulated class.

Encapsulation is also known as "Data hiding" because they are protecting data which is prone to change.

Example:


class Employee{
	private int employeeId;
	
	private String employeeName;
	
	private String designation;
	
	public int getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}
	public String getEmployeeName() {
		return employeeName;
	}
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}	
}		


Why Encapsulation use in Java Code?

Here are some advantages to use encapsulation in Java Code.

 - Encapsulated Code is more flexible and easy to change with new requirements.
 - By providing only getter and setter method access, you can make the class read only.
 - Encapsulation in Java makes unit testing easy.
 - A class can have total control over what is stored in its fields. Suppose you want to set the value of marks field i.e. marks should be positive value, than you can write the logic of positive value in setter method.
 - Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environments.
 - Encapsulation allows you to change one part of code without affecting other part of code.


Relation with Abstraction:

 - Abstraction is more about ‘What‘a class can do.

 - Encapsulation is more about ‘How‘to achieve that functionality.

Summary:

     - "Whatever changes encapsulate it" is a famous design principle.
     - Encapsulation in Java is achieved using access modifier private, protected and public.
     - Singleton pattern in Java makes good use of Encapsulation.