Lesson 18 / 38
Encapsulation
Hide internal state behind Java's four access levels — private, package-private, protected, public — and expose validated getters and setters.
Four access levels
private (same class), package-private (no keyword — same package), protected (package + subclasses), public (everywhere). Default to the most restrictive that works.
Getters & setters
Keep fields private and expose controlled accessors. A setter can validate; a getter can compute. This lets the internals change without breaking callers.
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("amt");
balance += amt;
}
}