Encapsulation
Encapsulation is the practice of hiding an object's internal state behind a controlled public API. You make fields private and expose only the operations callers are allowed to perform. This protects invariants and lets you refactor the internals without breaking callers.
Without encapsulation
public class BankAccount {
public double balance; // anyone can set it to anything
}
acct.balance = -999; // no way to prevent this
With encapsulation
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException();
balance += amount;
}
public boolean withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
public double getBalance() { return balance; }
}
Now the class enforces its own invariant — balance can only change via controlled operations.
Immutability — the strongest encapsulation
Make all fields final, set them only in the constructor, and provide no setters. The class is thread-safe for free, easy to cache, and impossible to corrupt.
Records as encapsulation shortcut
public record Point(int x, int y) {}
// Fields are private final; accessors are generated. Encapsulation in one line.
See the full encapsulation guide.