Encapsulation means the ‘encapsulating’ or ‘wrapping up’ of data. This is actually a mechanism that binds data together.
Encapsulation in Java is a mechanism to wrap up variables and methods together as a single unit. It is the process of hiding information details and protecting data and behavior of the object. It is one of the four important OOP concepts. The encapsulate class is easy to test, so it is also better for unit testing.
When encapsulation is implemented, only the variables inside the class can access it. No class outside the current class can access the variables inside it.
class Simple {
private String course;
public String getCourse() {
return course;
}
public void setCourse(String str) {
this.course = str;
}
}
public class Encapsulation {
public static void main(String[] args) {
Simple obj = new Simple();
//set data
obj.setCourse("Java");
//get data
System.out.println(obj.getCourse());
}
}
Output:
java
There are various reasons as to why encapsulation is essential in Java:
1. Encapsulation allows us to modify the code or A part of the code without having to change any other functions or code.
2. Encapsulation makes our applications simpler.
3. We can modify the code based on the requirements using encapsulation.
4. Encapsulation controls how we access data.
Getter and Setter in Java are two conventional methods used to retrieve and update values of a variable. They are mainly used to create, modify, delete and view the variable values. The setter method is used for updating values and the getter method is used for reading or retrieving the values. They are also known as an accessor and mutator.