Encapsulation in OOP — The Principle Explained
Encapsulation is the principle of bundling data and methods together and restricting direct access to the internal state. It’s the foundation of good OOP design.
The Analogy
Think of a capsule (medicine pill). It wraps the ingredients inside — you don’t touch the powder directly; you swallow the capsule. The capsule is the public interface; the powder is the private data.
Similarly, in OOP:
- Private fields = internal data (the powder)
- Public methods = controlled access (the capsule)
Without Encapsulation
class Employee {
String name;
double salary; // anyone can set this to anything!
}
Employee e = new Employee();
e.salary = -50000; // negative salary? No validation!
Problem: Anyone can set salary to any value — including invalid ones.
With Encapsulation
class Employee {
private String name;
private double salary;
public void setSalary(double salary) {
if (salary < 0) {
throw new IllegalArgumentException("Salary cannot be negative");
}
this.salary = salary;
}
public double getSalary() {
return salary;
}
}
Now salary is protected — only valid values are accepted.
Why Encapsulation Matters
- Data integrity — prevent invalid states
- Flexibility — change internals without breaking external code
- Debugging — if a field is wrong, only the setter could have changed it
- Security — hide sensitive data from unauthorized access
Encapsulation in Everyday Software
| System | Hidden (Private) | Exposed (Public) |
|---|---|---|
| ATM | Account database, encryption | PIN pad, screen, buttons |
| Car | Engine internals | Steering, pedals, dashboard |
| Phone | Circuit board, OS kernel | Touchscreen, apps |
| REST API | Database queries, business logic | HTTP endpoints |
Summary
- Encapsulation = data hiding + controlled access
- Use
privatefields +publicgetters/setters - Validates data, protects integrity, enables change
→ We’ll implement encapsulation fully in the Encapsulation Deep Dive chapters.
What’s Next?
Next principle: Inheritance — how to reuse code by building on existing classes.