Inheritance and Composition: Which One Should You Prefer?
June 03, 2026
The Classic Debate
"Favour composition over inheritance" is one of the most quoted pieces of advice in OOP. But what does it mean, and when should you use each?
Inheritance
Inheritance creates an "is-a" relationship. A Dog is an Animal. It promotes code reuse by allowing child classes to inherit behaviour from parent classes.
class Animal {
public string Name { get; set; }
public virtual void Breathe() => Console.WriteLine("Breathing...");
}
class Dog : Animal {
public void Fetch() => Console.WriteLine($"{Name} fetches the ball!");
}
Problem: Deep inheritance hierarchies become rigid and hard to change. If Animal changes, all subclasses are affected.
Composition
Composition creates a "has-a" relationship. Instead of inheriting behaviour, you build an object from other objects.
class Engine {
public void Start() => Console.WriteLine("Engine started.");
public void Stop() => Console.WriteLine("Engine stopped.");
}
class Car {
private readonly Engine _engine = new();
public string Model { get; set; }
public void Drive() { _engine.Start(); Console.WriteLine($"{Model} is moving."); }
public void Park() { _engine.Stop(); Console.WriteLine($"{Model} is parked."); }
}
Car has an Engine — it does not inherit from it. You can swap the engine type without changing Car.
When to Use Inheritance
- There is a clear and stable "is-a" relationship
- You want to enforce a contract with abstract methods
- The hierarchy is shallow (1–2 levels)
When to Use Composition
- You need flexibility to swap behaviour at runtime
- The relationship is "has-a" not "is-a"
- You want to avoid tight coupling between classes
Conclusion
Neither is universally better. Use inheritance for clear taxonomies and composition for flexible, decoupled designs. Most real-world systems use both.