Inheritance vs Composition
Two ways to reuse behaviour: extending a class (is-a) or holding other objects (has-a), and why composition is usually preferred.
What is it?
There are two main ways to build a class from existing behaviour:
- Inheritance ("is-a"): class Dog extends Animal. The subclass gets all of the parent's fields and methods and can override some. - Composition ("has-a"): class Car { engine: Engine }. The class holds other objects and delegates work to them.
Inheritance is tempting because it reuses code with one keyword, but it couples the subclass tightly to the parent's internals. When the parent changes, subclasses can break in surprising ways: the fragile base class problem. Inheritance is also fixed when the code is written; you can't swap a parent at run time.
Composition keeps parts independent and replaceable, so the common advice from Design Patterns (1994) is favour composition over inheritance.
Mixins and traits sit in between: small reusable bundles of methods you add to a class (Python mixin classes, Rust and Scala traits, PHP traits), giving reuse without a deep hierarchy.
Explain like I'm 10
Inheritance is being born into a family: you get all the traits, wanted or not, and can't change parents later. Composition is assembling a team: you pick a driver, a navigator and a mechanic, and you can replace any of them if a better one comes along.
Examples
Fragile base class: a subclass broken by the parent's internals
class Collection:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def add_all(self, items):
for item in items:
self.add(item) # internally calls add()
class CountingCollection(Collection):
def __init__(self):
super().__init__()
self.added = 0
def add(self, item):
self.added += 1
super().add(item)
def add_all(self, items):
self.added += len(items)
super().add_all(items) # which calls our add() again!
c = CountingCollection()
c.add_all(["a", "b", "c"])
print(c.added) # 6, not 3The same feature with composition
class CountingCollection:
def __init__(self, inner):
self._inner = inner # has-a Collection
self.added = 0
def add(self, item):
self.added += 1
self._inner.add(item)
def add_all(self, items):
for item in items:
self.add(item) # only our own methods, no hidden coupling
c = CountingCollection(Collection())
c.add_all(["a", "b", "c"])
print(c.added) # 3The wrapper only uses the inner object's public methods, so changes to how Collection is implemented internally can't break its counting.
Traits: shared behaviour without a hierarchy (Rust)
trait Describe {
fn name(&self) -> String;
fn describe(&self) -> String { // default method
format!("This is {}", self.name())
}
}
struct User { username: String }
struct Product { title: String }
impl Describe for User {
fn name(&self) -> String { self.username.clone() }
}
impl Describe for Product {
fn name(&self) -> String { self.title.clone() }
}How it works
With inheritance, the subclass and parent share one object. The parent's methods can call methods the subclass overrides, so the two are woven together: the subclass depends on when and how the parent calls its own methods, which is rarely documented and easy to change by accident.
With composition, the outer object holds a reference to the inner one and forwards calls explicitly (delegation). The only contract is the inner object's public interface. You can pass in a different implementation (dependency injection), wrap it for testing, or combine several behaviours without multiple inheritance.
Mixins and traits supply methods to a class without being its "parent" in the domain sense. Python mixins rely on multiple inheritance and the method resolution order (MRO); Rust traits are interfaces that can carry default methods and are implemented separately for each type.
Inheritance (is-a) Composition (has-a)
Animal Car
^ +--------------+
| extends | engine -----+--> Engine
Dog | wheels -----+--> Wheel[4]
| radio -----+--> Radio
fixed at compile time, +--------------+
shares internals parts swappable, uses public APIsWhy does it exist?
Inheritance was oversold in early OOP as the main tool for reuse, and large hierarchies proved hard to change: a modification at the top rippled through every subclass, and real-world categories rarely form a clean tree (is a flying penguin-robot a Bird or a Machine?). Composition emerged as the default because it keeps components loosely coupled and lets behaviour be mixed and swapped freely.
When to use it
Use inheritance for a genuine, stable "is-a" relationship where the subclass can be used anywhere the parent can (the Liskov substitution principle), typically shallow, and especially when a framework is designed for it (abstract base classes, UI component base classes). Use composition for everything else: adding behaviour, swapping implementations, wrapping for logging or caching, or combining features.
When not to use it
Don't inherit just to reuse a few methods, and don't inherit from classes not designed for extension (many standard library collections). Don't compose blindly either: writing dozens of forwarding methods to imitate an "is-a" relationship that really holds is just inheritance done the hard way.
Common mistakes
Using inheritance for code reuse when there's no real is-a relationship (e.g.
Stack extends ArrayList, which exposes methods that break stack behaviour).Building deep hierarchies (five or more levels) where understanding one class means reading all its ancestors.
Overriding a method without knowing which other parent methods call it, causing double-counting or recursion bugs.
Creating a subclass that can't honour the parent's contract (a
Squarethat breaksRectangle's independent width and height), violating Liskov substitution.Mixing many Python mixins without understanding the MRO, so it's unclear which method actually runs.
Practice exercises
- Easy:
For each pair decide whether it's is-a or has-a: Car/Engine, Manager/Employee, Order/LineItem, Circle/Shape, Logger/FileWriter.
- Medium:
Refactor a
LoggingList extends list(Python) orLoggingArray extends Array(JS) into a class that composes a list and logs every add and remove. - Hard:
Design game characters that can fly, swim and/or attack in any combination, first with inheritance and then with composition (behaviour objects or traits). Compare how many classes each approach needs for 5 abilities.
Interview questions
What is the difference between inheritance and composition?
Inheritance creates an is-a relationship where a subclass reuses and specialises a parent class. Composition creates a has-a relationship where a class holds other objects and delegates to them through their public interfaces.
What does 'favour composition over inheritance' mean?
Prefer building behaviour by combining objects rather than extending classes, because composition gives looser coupling, run-time flexibility and fewer surprises when parts change. Use inheritance only for real, stable is-a relationships.
What is the fragile base class problem?
Changes to a base class's implementation (not just its interface) can break subclasses, because subclasses depend on internal details like which methods call which. The parent can't safely evolve without knowing every subclass.
What is the Liskov substitution principle?
Objects of a subclass should be usable anywhere the parent type is expected without breaking correctness. A subclass must keep the parent's promises: no stronger preconditions, no weaker postconditions.
Why is Square extending Rectangle a classic problem?
A Rectangle lets you set width and height independently. A Square must keep them equal, so code that sets width then height on what it thinks is a Rectangle gets a wrong area. Square can't honour Rectangle's contract.
What is a mixin?
A small class that provides a specific set of methods to be combined into other classes, usually through multiple inheritance, without being a meaningful parent type. For example a JsonSerializableMixin adding to_json().
What is a trait (in Rust or Scala)?
A named set of methods a type can implement, optionally with default implementations. Types gain shared behaviour by implementing traits, without a class hierarchy. Rust has no struct inheritance at all; traits are its main reuse mechanism.
What is delegation?
An object handling a request by forwarding it to another object it holds. It's the mechanism behind composition, and the basis of patterns like Decorator, Strategy and Proxy.
When is inheritance the right choice?
When there's a genuine is-a relationship that satisfies Liskov substitution, the hierarchy is shallow and stable, or a framework is explicitly designed for extension through subclassing (template methods, abstract base classes).