Encapsulation in Java is a process of wrapping the data and code in a single unit. The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. It is one of the four important OOPs concept.
To achieve encapsulation in Java −
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
The get method returns the variable value, and the set method sets the value.
Syntax of get method – method name starts with get followed by the variable name where first letter is capital.
Syntax of set method – method name starts with set followed by the variable name where first letter is capital.
Below is an example of encapsulation with two variables and their getter and setter method.
public class EncapsulationDemo {
// private variables
private String name;
private int age;
// getter method for age
public int getAge() {
return age;
}
// setter method for age
public void setAge(int setAge) {
this.age = setAge;
}
// getter method for name
public String getName() {
return name;
}
// setter method for name
public void setName(String newName) {
this.name = newName;
}
}
The variables of the EncapsulationDemo class can be accessed using the following program −
public class EncapsulationTest {
public static void main(String[] args) {
//creating instance of the encapsulated class
EncapsulationDemo encap = new EncapsulationDemo();
//setting value in the age member
encap.setAge(25);
//setting value in the name member
encap.setName("Terry");
//getting value of the age and name member
System.out.print("Name : " + encap.getName() + " and Age :" + encap.getAge());
}
}
Output
Name : Terry and Age :25
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE’s are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.