Java Encapsulation
Encapsulation bundles data (fields) and methods that operate on that data within a class, while restricting direct access to internal state using private fields and public getter/setter methods.
This protects an object's internal consistency, since all access to its data goes through controlled methods that can validate input.
private type field;
public type getField() { return field; }
public void setField(type value) { field = value; }Private fields, public methods
Marking fields private prevents external code from modifying them directly. Getters and setters expose controlled access, optionally with validation.
Benefits of encapsulation
Encapsulation hides implementation details, allows internal changes without breaking external code, and enables validation logic in setters.
class Person {
private int age;
public void setAge(int age) {
if (age >= 0) this.age = age;
}
public int getAge() { return age; }
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setAge(25);
System.out.println(p.getAge());
}
}25age is private and can only be changed through setAge, which validates the input.
Key points
- Encapsulation hides internal state behind private fields.
- Getters and setters provide controlled access.
- Setters can validate data before assignment.
- Encapsulation improves maintainability and safety.
