Encapsulation is another basic principle of object-oriented programming. It involves hiding data from external access.
Introducing encapsulation in Java is extremely important, especially in large projects.
By following the encapsulation rules, we ensure that objects have strictly controlled inputs and outputs and thus reduce the possibility of error, logical inconsistency, or errors in the program.
We provide data hiding by using the keyword private. That way, no one outside that class can change the data unplanned.
Each access to data is done exclusively through public methods created for these purposes, which are getter and setter methods.
The getter method is used to retrieve data, i.e. it returns the value of a variable, while the setter method is used to set a new value for the variable.
We can make the class read-only or write-only by providing only the setter or getter method. In this way, we provide control over the data.
Example:
public class Student { private String name; public String getName() { return name; } public void setName(String name) { this.name = name } } class Test { public static void main(String[] args) { Student s = new Student(); // System.out.println(s.name); // DOES NOT COMPILE s.setName("John"); System.out.println(s.getName()); } }
That’s it!