What does "favor composition over inheritance" mean? Give an example of inheritance causing harm?
Short answer
Prefer holding another object and delegating to it (has-a) over inheritance (is-a). Inheritance ties the subclass to the parent's details; composition lets you combine behavior at runtime, test pieces alone, swap easily.
3 points to say:
- Inheritance is the strongest coupling: fragile base class, the subclass breaks when the parent's implementation changes.
- Composition = hold and delegate; inheriting just to reuse code makes the number of classes explode.
- Inherit only when is-a holds for behavior (LSP) and the parent is designed for inheritance; otherwise make it
final.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.