Encapsulation is one of the four fundamental OOP concepts. Encapsulation in Java is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users. For this, Encapsulation is also known as data hiding.
Implementing the encapsulation in the program, the variables or data declared in one of the classes is hidden from any other class.
Encapsulation can be achieved in two ways:
- Declare class variables/attributes as private, restricting other classes to access it.
- Provide public setter and getter methods to modify and view the values of the variables.
Benefits of Encapsulation:
- Data- hiding in Java.
- The class field can be made read-only or write-only.
- It provides the class the total control over the data.
Get and Set:
As we know the private variable cannot be accessed by other classes, but we can access them by providing getter and setter methods.
- The get method returns the variable value.
- The set method sets the value.
Getter and Setter methods should start with get or set, followed by the variable name whose first letter should be in upper case. They both should be declared public. Since get returns value and set doesn’t get should be of data-type same as the variable it accesses and set must be declared void.
public class Student
private String name; // private
public String getName()
public void setName(String newName)
this.name = newName;
Let us go through a java example to understand better
Encapsulation in Java using setter and getter
private int id;
private String stdName;
private int stdAge;
public int geStdiID()
public String getStdName()
public int getStdAge()
// Setter methods
public void geStdiID(int newId)
id = newId;
public void getStdName(String newName)
stdName = newName;
public void getStdAge(int newAge)
stdAge = newAge;
public class EncapsTest
public static void main(String args)
StudentInfo obj = new StudentInfo();
System.out.println("Student Id: " + obj.geStdiID());
System.out.println("Student Name: " + obj.getStdName());
System.out.println("Student Age: " + obj.getStdAge());
Student Id: 1101
Student Name: Marshall
Student Age: 20