Lesson content
Read, practise, then check your understanding
Encapsulation hides representation behind operations that maintain valid state. private is narrowest, no modifier gives package-private access, protected adds subclass access under specific rules, and public exposes an API wherever its type is visible.
Preserve invariants
public final class Percentage {
private final double value;
public Percentage(double value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("0..100 required");
}
this.value = value;
}
public double value() { return value; }
}
Do not create setters mechanically; expose meaningful domain operations. Make defensive copies of mutable inputs and outputs, or use immutable types. Package-private helpers support cohesive internal collaboration without becoming public contracts. Protected fields couple subclasses to representation, so prefer private state with protected behavior. Keep APIs minimal, stable, documented, and free of implementation types that would prevent future refactoring.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.