SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 8 / 42

Middle

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.

YesNoNeed to reuse behaviorTrue behavioral is-aand parent built for it?InheritanceComposition:hold and delegate

3 points to say:

  1. Inheritance is the strongest coupling: fragile base class, the subclass breaks when the parent's implementation changes.
  2. Composition = hold and delegate; inheriting just to reuse code makes the number of classes explode.
  3. 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.