Composition vs Inheritance — What's the Difference?
Inheritance builds new classes on top of existing ones through an "is-a" relationship; composition builds behavior by combining separate objects through a "h...
Published November 22, 2026
Inheritance models an 'is-a' relationship by extending a parent class; composition models 'has-a' by building objects from other objects. Prefer composition for flexibility and reserve inheritance for true specialisation.
The concept
Inheritance couples a child tightly to its parent: changes in the parent can break children, and you cannot inherit from several classes in many languages.
Composition assembles behaviour from small parts you can swap at runtime, which is easier to test and change.
Is-a vs has-a
Practical examples
Inheritance
class Animal { eat() {} }
class Dog extends Animal { bark() {} }Composition
const canFly = (s) => ({ fly: () => `${s.name} flies` })
const canSwim = (s) => ({ swim: () => `${s.name} swims` })
const duck = { name: 'Duck' }
Object.assign(duck, canFly(duck), canSwim(duck))Inject a dependency
class Car { constructor(engine) { this.engine = engine } start() { this.engine.ignite() } }Common mistakes
- Deep inheritance trees.
- Inheriting just to reuse a method.
- Overriding methods in ways that break the parent's contract.
Key takeaways
- Inheritance = is-a, composition = has-a.
- Prefer composition.
- Use inheritance for real specialisation.
FAQ
Is inheritance bad?
No, it is a good fit when a true is-a relationship exists.
What are mixins?
A way to share behaviour without deep hierarchies.