Encapsulation hides internal state behind methods—typically private fields with public getters/setters. This mirrors PHP visibility keywords but is idiomatic Java: never expose mutable fields publicly unless they are final value objects.
Access modifiers
private— class onlypackage-private(default) — same packageprotected— subclass + packagepublic— everywhere
Getter/setter pattern
class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
}
Validate in setters—do not allow negative balances through a raw public field.
Important interview questions and answers
- Q: Why encapsulate?
A: Preserve invariants, hide implementation, and reduce coupling for maintainability. - Q: Are getters always needed?
A: Prefer methods that express intent (deposit) over exposing raw mutable state.
Self-check
- Which modifier hides a field from other classes?
- Where should validation live—in the setter or the caller?
Pitfall: Exposing public mutable fields bypasses validation—use methods like deposit to enforce invariants.
Interview prep
- Why private fields?
Encapsulation preserves invariants—callers use methods that validate input instead of mutating raw state that can break object rules.