← Back to Roadmap

Composition vs Inheritance

Medium

In plain terms

Inheritance is "is-a" (Dog is an Animal). Composition is "has-a" (Car has an Engine). With composition, you do not subclass; instead, your class holds one or more other objects and delegates work to them.

"Favor composition over inheritance" is a common design guideline. Deep inheritance trees become hard to change; composition is more flexible. You can swap or add components without touching the class hierarchy. Use inheritance when you truly have a subtype relationship; use composition when you are combining capabilities.

What you need to know

  • Inheritance: is-a
  • Composition: has-a
  • Prefer composition when it fits better

Example

Code is language-agnostic in spirit; adapt the idea to your language:

// Composition: Car HAS-A Engine
class Engine {
  start() { return "Engine started"; }
}
class Car {
  constructor() {
    this.engine = new Engine();
  }
  start() {
    return this.engine.start();
  }
}
// No inheritance; Car uses Engine

Why this matters

"Favor composition over inheritance" is a classic interview question. Senior roles expect you to explain when each is appropriate and to avoid overusing inheritance.

How it connects

Composition supports Single Responsibility (each component has one job) and avoids the fragility of deep inheritance. Dependency Inversion often uses composition: inject dependencies rather than inheriting from a base that does everything.

Interview focus

Be ready to explain these; they come up often.

  • Inheritance = is-a; composition = has-a. Use the one that matches the relationship.
  • Composition is more flexible: swap parts, no fragile base class, easier testing.
  • Example: Car has-an Engine (composition) vs Car extends Vehicle (inheritance).

Learn more

Dive deeper with these resources: