Encapsulation is the OOP principle of hiding internal data and exposing access through controlled methods. It helps keep the internal state of an object safe and secure from unintended interference.

Key Concepts

  • Make fields private.
  • Provide public getters/setters.
  • Keeps data safe and modular.

Example

public class Person {
    private String name;
    
    public String getName() {
        return name; // getter 
    }
    
    public void setName(String name) {
        this.name = name; // setter
    }
}
 
Person person = new Person();
person.setName("Kamil");
System.out.println(person.getName()); // "Kamil"

Benefits

  • Protects internal state.
  • Allows validation in setters.
  • Easy to refactor;
  • Improves code maintainability and modularity.

Real-World Analogy

Think of a capsule pill - you only interact with the outside, not with the ingredients directly.

Tip

If you’re using private fields + public getters/setters, you’re applying encapsulation. Be ready to explain how it promotes security, clean APIs and code reuse.


Parent: _OOP Concepts