Encapsulation (Java)
Encapsulation is the practice of hiding an object's internal data and exposing it only through controlled methods. In Java, you do this by making fields private and providing public getters and setters.
Java
By controlling access to its data, a class can validate changes and prevent the rest of the program from putting it into an invalid state. The outside world interacts with the object's behavior, not its raw fields.
Encapsulation is one of the four pillars of object-oriented programming, alongside inheritance, polymorphism, and abstraction.
Examples
Java
public class Person {
private int age;
public void setAge(int age) {
if (age >= 0) this.age = age;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
Person p = new Person();
p.setAge(30);
System.out.println(p.getAge());
}
}Output:
30