Explore Topics
Encapsulation is the bundling of data (fields) and the methods that operate on that data into a single unit (a class), while restricting direct access to internal state. A fully encapsulated class makes ALL fields private and provides controlled access through public methods. This is not just about adding getters and setters — it means the class controls its own invariants. For example, a BankAccount with deposit() and withdraw() methods can enforce "balance never goes negative," which a public field never could.
- Encapsulation = data + methods bundled together in one class
- All fields private — no direct access from outside
- Public methods provide controlled access with validation
- The class enforces its own invariants (rules that must hold)
- Fully encapsulated class: every field is private
- No setBalance() — state changes only through meaningful operations
- Encapsulation prevents invalid state (e.g., negative balance)
- ✦Protects data integrity — invalid state cannot be set from outside
- ✦Simplifies debugging — state changes happen in one place
- ✦Enables validation logic in methods (deposit checks amount > 0)
- ✦Reduces coupling — clients depend on the interface, not the fields
- △Requires upfront design of the public API
- △Can feel verbose for simple data-holder classes
- △Over-encapsulation (unnecessary indirection) adds complexity
- △Reflection can bypass private access (a known escape hatch)
Quiz
class Counter {
private int count = 0;
public void increment() { count++; }
public int getCount() { return count; }
}
Counter c = new Counter();
c.increment();
c.increment();
System.out.println(c.getCount());