Encapsulation
Encapsulation keeps an object's data hidden and lets callers change it only through methods that enforce rules. Fields stay private; the public surface is the contract.
Detailed Explanation
If balance is public, any line in the program can set it to -1. If balance is private and the only writer is withdraw, you can refuse overdrafts in one place. Encapsulation is that door. The class owns the data. Everyone else knocks.
Java enforces this with access modifiers. private is the default you should mean for fields. Package-private (no modifier) is visible to the whole package, which is wider than most people think. protected is visible to subclasses and the package. public is visible everywhere. Getters and setters are not encapsulation by themselves. A pair of public getX/setX methods on every field is a public field with extra typing. Encapsulation starts when some states are impossible to represent from outside.
Invariants belong next to the fields. "Amount is never negative" is an invariant. Constructors establish it. Mutators preserve it. If a method can leave the object invalid, the door is open. Immutable types go further: after construction, nothing can change, so aliasing is safe. Records give you that shape for data carriers, still with private final fields.
You reach for encapsulation when more than one method must agree on a rule, or when you may change representation later (store paise instead of rupees, cache a derived value, replace a list with a set). You keep a field visible only when the type is a simple data bag used inside one package and the cost of methods would hide nothing.
The cost of over-encapsulation is ceremony. A one-field private class with a getter, used once, is noise. The cost of under-encapsulation is coupling: a refactor of a field name or a unit change becomes a sweep of the whole codebase. Start fields private. Open them when a caller inside the same module truly needs them, and prefer a method named after the intent (refund, markPaid) over setStatus.
Encapsulation also applies at package and module scale. A public class in a published library is forever. JPMS modules can hide packages entirely. Treat public as a promise, not a default.
Code Examples
public class Account {
private int balancePaise; // hidden; no caller can assign this field
public Account(int balancePaise) {
if (balancePaise < 0) {
throw new IllegalArgumentException("balance must be >= 0");
}
this.balancePaise = balancePaise;
}
public void withdraw(int paise) {
if (paise > balancePaise) {
throw new IllegalArgumentException("insufficient funds");
}
balancePaise -= paise; // the only legal way to reduce the balance
}
public int balancePaise() {
return balancePaise; // read is allowed; write is not
}
public static void main(String[] args) {
Account a = new Account(500);
a.withdraw(200);
System.out.println(a.balancePaise()); // prints: 300
}
}import java.util.ArrayList;
import java.util.List;
public class Team {
private final List<String> members = new ArrayList<>();
public void add(String name) {
members.add(name);
}
// Return a snapshot so a caller cannot clear the real list.
public List<String> members() {
return List.copyOf(members);
}
public static void main(String[] args) {
Team t = new Team();
t.add("Rin");
System.out.println(t.members()); // prints: [Rin]
}
}Common Gotchas
Getters that return a live collection leak mutation
`return members` lets the caller `clear()`. Return a copy or an unmodifiable view.
Package-private fields are not private
any class in the same package can write them, including tests and later helpers.
Records encapsulate storage, not behaviour
components are still exposed through accessors. Put rules in a compact constructor.
Public mutable fields skip every invariant
a future check in a setter never runs for those assignments.