Skip to content
We areTOP 1%

Why is composition often preferred over inheritance?

MediumConceptOOP & SOLID
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

Inheritance creates a tight, compile-time is-a coupling between classes, while composition builds behaviour from smaller objects held as fields (a has-a relationship) that can be swapped at run time. Composition therefore tends to produce more flexible designs.

  • Fragile base class: changes to a parent class can silently break subclasses that rely on its internals.
  • Class explosion: combining features through inheritance (for example, FlyingSwimmingDuck) multiplies subclasses, whereas composing a FlyBehavior and a SwimBehavior does not.
  • Run-time flexibility: a composed strategy object can be replaced without changing the class, which is the basis of the Strategy and Decorator patterns.
  • Use inheritance when there is a genuine, stable is-a relationship and subclasses honour the Liskov Substitution Principle.

More in OOP & SOLID

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account