Encapsulation in Practice
Prerequisites: Interfaces
Beyond simply making fields private, real encapsulation means the
getters and setters actually enforce invariants rather than just
passing values through unchanged:
class BankAccount {
private double balance;
public void setBalance(double balance) {
if (balance < 0) {
throw new IllegalArgumentException("Balance cannot be negative");
}
this.balance = balance;
}
public double getBalance() {
return balance;
}
}
Not every field needs both a getter and a setter — an immutable class (see Records, in Level 3) only exposes getters, and every field is set once, in the constructor, and never changed again.
Common mistakes
- Generating a setter for every field automatically (IDEs offer to do this) without considering whether that field should actually be changeable from outside the class at all.