Encapsulation

Encapsulation in Java is a concept of wrapping the data and methods together as a single unit. In other words we can say it is a mechanism that binds together variable data and methods.

Example:

  • Make the instance variable as private so that they can not accessed directly from the outside. We can only set and get the value of the fields.
  • Getter and setter methods in the class is used to get and set the values.
  • In encapsulation, data in a class is hidden from other classes, Hence it is also known as data-hiding.

Let’s see an example

public class Encapsulation {

	private int rollNo;
	private String name;


	public int getRollNo() {
		return rollNo;
	}

	public void setRollNo(int rollNo) {
		this.rollNo = rollNo;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}
}

In the above example the class is encapsulated as the variables are declared as private. The get methods like getRollNo() and getName() are set as public, these methods are used to access these variables. The setter methods like setRollNo() and setName() are also declared as public and are used to set the values of the variables.

The program to access above variables is as below:

public class EncapsulationTest {

	public static void main(String[] args) {
		Encapsulation obj = new Encapsulation();

		// Setting values
		obj.setRollNo(101);
		obj.setName("Harry");

		// Displaying values
		System.out.println("Roll No " + obj.getRollNo());
		System.out.println("Name " + obj.getName());

	}

}
Output:

Roll No 101

Name Harry

Advantages of Encapsulation

1. Re-usability

Encapsulation increase the reusability of the code and we can update the code as per the requirements.

2. Data Hiding

Data hiding is a concept where end user does not have any idea regarding the inner implementation of the class. End user will only see the values which are passing in the setter method and getting the corresponding values from the getter method.

3. Code flexibility

With the help of encapsulation feature we can make the variable of the class as read only or write only as per our requirements. We can provide the access of setter method to the user to make our variable as write only and if we want to make our variable as read only then we will not provide the access of setter method like setRollNo() and setName() methods.