Video in progress
How do you design a class that other teams will inherit from, so their code doesn't break in the next version?
I decide on inheritance deliberately: I expose the extension points as explicit protected hooks, make everything else final, and document self-use. Or I close inheritance entirely and offer an interface and composition.
📖 Answer
This is called the "fragile base class" problem: whether one method calls another inside the base class is an implementation detail, but the subclass ends up bound to exactly that.
A classic example:
class CountingSet<E> extends HashSet<E> {
int added;
@Override public boolean add(E e) { added++; return super.add(e); }
@Override public boolean addAll(Collection<? extends E> c) {
added += c.size();
return super.addAll(c); // add() is called inside, so it's counted twice
}
}
If the base class author changes the insides of addAll, the subclass silently behaves differently.
My rules:
- The default is
final. A class open for inheritance is a public contract, and you have to maintain it for years. - Template method. If I leave it open, the main method is
finaland extension only happens through explicitprotectedhooks:beforeSave(),validate(). - Write down self-use. State clearly in the javadoc that "this method calls
add": the@implSpectag exists for exactly this. - Don't call overridable methods in a constructor: the subclass's fields haven't been initialized yet.
- Sealed classes (Java 17) when you need to control who can inherit.
In practice the best answer is often an interface and delegation instead of inheritance: the user writes their own class and your class calls it internally.
Sign up to mark studied questions and save your progress.