Why is composition often preferred over inheritance?
MediumConceptOOP & SOLID
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 aFlyBehaviorand aSwimBehaviordoes 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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What are the four pillars of object-oriented programming? | Concept | Easy | Read the answer to What are the four pillars of object-oriented programming? | |||
| 2 | What is the difference between an abstract class and an interface? | Concept | Easy | Read the answer to What is the difference between an abstract class and an interface? | |||
| 3 | What are the SOLID principles? | Concept | Medium | Read the answer to What are the SOLID principles? | |||
| 4 | Why is composition often preferred over inheritance? | Concept | Medium | Read the answer to Why is composition often preferred over inheritance? |