Inheritance and composition are the two ways an object-oriented class can reuse behavior. With inheritance a class is a specialized version of another class and gets its code by extending it. With composition a class has other objects as parts and gets work done by calling them (delegation). Inheritance is fixed when you write the class and allows one parent; composition is decided when you build the object and can change while it runs. That is why the Gang of Four's advice, "favor object composition over class inheritance", is still the default rule in modern design, and why most of the patterns in this track are built on it.
Think of it like
A power drill and its bits
Imagine buying a separate drill for every job: one that drills wood, one that drives screws, one that does both, one that sands, one that drills and sands... Each new job doubles the shelf. Instead, a real drill has a chuck, and you clip in whichever bit the job needs, even halfway through the job. The drill is the composed object, the chuck is the interface, each bit is a part, and swapping bits is changing behavior at runtime. A buy-a-new-drill-for-each-combination shop is a class hierarchy.
The problem
A game has heroes that can fly or swim, and some can do both. The first design that comes to mind is a class hierarchy: an abstract Hero with one subclass per kind of hero. This is the Before version in the visualizer above.
abstract class Hero {
constructor(protected name: string) {}
abstract moves(): string[];
}
class FlyHero extends Hero {
moves() {
return [`${this.name} flies`];
}
}
class SwimHero extends Hero {
moves() {
return [`${this.name} swims`];
}
}
class FlySwimHero extends Hero {
moves() {
// copied from FlyHero and SwimHero
return [`${this.name} flies`, `${this.name} swims`];
}
}
let kai: Hero = new FlyHero("Kai");
kai = new FlySwimHero("Kai"); // power-up: a new object of another class
kai.moves(); // ["Kai flies", "Kai swims"]It works, and with two abilities it even looks tidy. The trouble is structural, and it grows with every ability:
- A class per combination. Abilities can be mixed, so the hierarchy needs a class for every mix. A third ability turns 3 subclasses into 7.
- Copied code.
FlySwimHerocannot extend bothFlyHeroandSwimHero(Java, C# and TypeScript allow one superclass), so it copies one or both. A bug fix in the flying code must now be made in every class whose name containsFly. - Behavior is frozen at construction. An object's class is fixed when it is created. When Kai picks up a power-up, the code cannot add swimming to Kai: it builds a new
FlySwimHeroand must copy health, position and everything else across by hand. - The base class leaks. Every subclass depends on
Hero's internals (here theprotected name). ChangingHerocan break subclasses you have never seen.
| Abilities (n) | Subclasses needed (2ⁿ − 1) | Ability parts with composition (n) |
|---|---|---|
| 2: fly, swim | 3 | 2 |
| 3: + climb | 7 | 3 |
| 4: + dig | 15 | 4 |
| 5: + teleport | 31 | 5 |
Hero class and the Ability interface.Is-a vs has-a
The quickest test is to say the relationship out loud. If "a B is a A" is true everywhere an A is used, inheritance can model it. If "a B has a A" (or uses one) sounds right, use a field and call it.
- Inheritance (is-a)
- A subclass extends a superclass, gets its fields and methods, and can override them. The link is static: written in the class declaration, one parent in most languages, and the same for every instance.
- Composition (has-a)
- A class holds references to other objects in its fields and builds its behavior out of them. The link is dynamic: decided when the object is built and changeable afterwards.
- Delegation
- Forwarding a request to a part instead of handling it yourself:
Hero.moves()callsmove()on each ability. Delegation is what makes composition do work. - White-box vs black-box reuse
- The Gang of Four's terms. A subclass sees, and depends on, its parent's internals (white box). A composed object only sees its parts' public interface (black box).
| Relationship | Is-a or has-a? | Why |
|---|---|---|
SavingsAccount and Account | Is-a | A savings account can be used anywhere an account can |
Car and Engine | Has-a | A car is not an engine; it owns one and could get a new one |
Hero and flying | Has-a | Flying is something a hero can gain and lose, so it is a part |
Stack and Vector in Java | Has-a (Java chose is-a) | java.util.Stack extends Vector, so a stack also exposes insertElementAt and remove(int), which break stack order. The Javadoc now recommends Deque instead |
Square and Rectangle | Careful | True in geometry, but if Rectangle has setWidth, a square cannot honor it. Is-a must hold for behavior, not just for the words |
Composition and delegation
Turn each ability into its own small class behind one interface, and give Hero a list of them. Hero no longer contains any movement code: it asks each part to do its job.
interface Ability {
move(who: string): string;
}
class Fly implements Ability {
move(who: string) {
return `${who} flies`;
}
}
class Swim implements Ability {
move(who: string) {
return `${who} swims`;
}
}
class Hero {
constructor(
private name: string,
private abilities: Ability[],
) {}
gain(a: Ability) {
this.abilities.push(a);
}
lose(a: Ability) {
this.abilities = this.abilities.filter((x) => x !== a);
}
moves() {
return this.abilities.map((a) => a.move(this.name));
}
}
const fly = new Fly();
const kai = new Hero("Kai", [fly]);
kai.gain(new Swim()); // power-up: same object, one more part
kai.moves(); // ["Kai flies", "Kai swims"]
kai.lose(fly); // wings break
kai.moves(); // ["Kai swims"]Three things changed. Each ability's code exists once, in its own class. A combination is now data (which objects are in the list), not a class. And because the list is an ordinary field, the combination can change while the program runs without creating a new hero. Hero depends only on the Ability interface, which is the first Gang of Four principle at work: program to an interface, not an implementation (see Interfaces & Abstract Classes). Press Play in the visualizer at the top of the page, or step with the arrow keys, to watch this exact code run; the caption under the stage explains each step.
What to watch in the visualizer
- Class diagram:
Herois joined to theAbilityinterface by a hollow diamond labeled0..*, andFlyandSwimimplement the interface. Whenkaicallsmove, the diamond lights up,Ability.moveturns violet (the interface declares it) and the part that actually runs turns amber. - Objects at runtime:
kaisits in the middle with its parts around it. Watch itsabilitiesfield:[fly], then[fly, swim]aftergain(swim), then[swim]afterlose(fly). The arrows from the field move with it. It is always the samekaiobject. - Sequence of calls: each
moves()from the client fans out into onemove("Kai")per part, and the list of answers goes back to the client:["Kai flies", "Kai swims"], then["Kai swims"]. - Before: switch to Before to see the inheritance version. There are no calls between objects at all, but the client creates
kai,kai2andkai3: one new object, of a different class, each time an ability changes.
- 1
Create the parts
The client creates
flyandswim. They have no fields: each holds only its own movement code. - 2
Build the hero
new Hero("Kai", [fly])makeskaiwithabilities = [fly]. Callingkai.moves()makeskaicallfly.move("Kai"), which returns"Kai flies". - 3
Add a part at runtime
kai.gain(swim)pushesswiminto the list. No class was written for flying and swimming together. - 4
Delegate to every part
kai.moves()loops overabilitiesand callsmoveon each part through theAbilityinterface. It returns["Kai flies", "Kai swims"]. - 5
Remove a part at runtime
kai.lose(fly)replaces the list with[swim]. The nextmoves()returns["Kai swims"]. Kai's name, and any other state, never had to be copied. - 6
Add a new ability (change request)
With Add climbing applied, one new class
Climbappears. The client plugs aclimbpart into the samekai, andmoves()returns["Kai swims", "Kai climbs"].
Before and after
Inheritance (one subclass per combination)
- Behavior is chosen by picking a class, once, at construction
- Each ability's code is copied into every combination that uses it
- A new ability adds a subclass for every new combination
- Changing abilities means building a new object and copying state
- Fewer objects and no indirection: simple while there are two cases
Composition (one part per ability)
- Behavior is the set of parts the object holds, which can change
- Each ability's code exists in exactly one class
- A new ability adds one class; combinations come for free
- Parts are tested alone;
Herois tested with fake parts - More small objects, and the parts must be created and wired up
| Change request: add climbing | Inheritance | Composition |
|---|---|---|
| Existing classes edited | 0 | 0 |
| New classes | 4 (ClimbHero, FlyClimbHero, SwimClimbHero, FlySwimClimbHero) | 1 (Climb) |
| Lines changed in existing classes | 0 | 0 |
| Classes in the diagram afterwards | 8 | 5 (including the interface) |
| Copies of the climbing code | 4 | 1 |
Notice what the panel does not show: neither version had to edit an existing class. Inheritance is perfectly good at adding new classes, so the cost of the Before design is not edits. It is the number of classes (four for one feature, and eight more for a fourth ability), the copied code that every future fix must chase, and the fact that a hero still cannot change its abilities without becoming a different object.
When inheritance is the right tool
"Favor composition" does not mean "never inherit". Inheritance is the simpler, clearer choice when the is-a relationship is real and stable:
- A true is-a that respects substitution. Every subclass can stand in for the parent without surprising its callers, which is the Liskov substitution principle in SOLID Principles. Exception hierarchies are the classic case: a
FileNotFoundExceptionreally is anIOException, andcatch (IOException e)should catch it. - A fixed algorithm with a few overridable steps. Template Method puts the skeleton in a base class and lets subclasses fill in the steps. The base class is designed and documented for extension.
- Framework extension points. Frameworks often ask you to subclass: override
doGetin a JavaHttpServlet, extendActivityon Android, subclass a Django class-based view. The framework owns the base class and documents which methods are meant to be overridden. - A small, closed hierarchy you control. A
ShapewithCircleandPolygon, defined together, oftensealed(Java 17, Kotlin, C#) so nobody else can extend it.
abstract class Report {
// The fixed skeleton. Subclasses fill in one step.
render(rows: string[]): string {
return [this.header(), ...rows.map((r) => this.row(r))].join("\n");
}
protected header(): string {
return "REPORT";
}
protected abstract row(r: string): string;
}
class CsvReport extends Report {
protected row(r: string): string {
return r.split(" ").join(",");
}
}Pitfalls of each
Inheritance
- Fragile base class
- A harmless-looking change in a base class breaks subclasses, because they depend on how it works inside, not just on what it promises. Joshua Bloch's Effective Java shows a
HashSetsubclass that counts additions by overridingaddandaddAll: after adding three elements it reports six, because the inheritedaddAllcallsaddinternally. The second implementation below reproduces it and fixes it with a wrapper. - Inheritance breaks encapsulation
- The Gang of Four's phrase for the same root cause: a subclass sees protected fields and the order in which the parent calls its own methods, and comes to rely on them.
- Deep hierarchies
- Five levels of
extendsmake it hard to answer "what does this object do?" without reading every ancestor. Each level also inherits every method above it, wanted or not. - Yo-yo problem
- Following one call through a deep hierarchy means bouncing up and down: a method in the child calls an inherited method in the grandparent, which calls an overridden method back in the child.
- Refused bequest
- A subclass inherits methods it does not want and overrides them to throw (a read-only list that extends a mutable one). A sign that is-a was the wrong relationship.
Composition
- Indirection. Behavior is spread over several small classes, so reading one class no longer tells you everything an object does. Good names and a clear interface are what keep this readable.
- Wiring. Someone has to create the parts and plug them in. In a large app that is a factory or a dependency injection container (Dependency Injection); done ad hoc, construction code gets messy.
- Forwarding boilerplate. A wrapper that must expose most of the inner object's interface needs one forwarding method per method. Kotlin generates them with
class CountingSet(inner: MutableSet<String>) : MutableSet<String> by inner, and Go promotes the methods of an embedded field. - Interfaces designed too early or too wide. One part interface per ability is cheap; a ten-method interface that every part half-implements is not. Keep part interfaces small and focused.
- Using it where nothing varies. An interface, a factory and three part classes for behavior with one variant is harder to read than a plain class. Composition pays off when behavior varies independently, changes at runtime, or would otherwise be copied; until then the simplest design wins (see DRY, KISS, YAGNI & the Law of Demeter).
In real code
| Where | What it shows |
|---|---|
| Design Patterns (Gamma, Helm, Johnson, Vlissides, 1994) | States the principle directly: "Favor object composition over class inheritance." It is the book's second principle, after "Program to an interface, not an implementation." |
| Effective Java (Joshua Bloch) | Has an item titled "Favor composition over inheritance", built on the counting HashSet example, and a follow-up: design and document for inheritance, or else prohibit it. |
| Java I/O streams | Features are composed by wrapping, not by subclass combinations: new BufferedInputStream(new FileInputStream("data.bin")). Buffering, decompression (GZIPInputStream) and typed reads (DataInputStream) stack in any order. This is Decorator. |
| React | The original React docs page "Composition vs Inheritance" says the team had not found use cases where they would recommend component inheritance hierarchies; components are combined through props and children instead. |
| Go | There is no class inheritance. A struct can embed another type, whose methods are promoted to the outer struct, and the standard library's bufio.ReadWriter is a struct embedding a *Reader and a *Writer. |
| Rust | Structs cannot inherit from structs. Shared behavior comes from traits (with default methods) and from holding other values as fields. |
| Game engines | Unity builds a GameObject by attaching components (Rigidbody, Collider, your own scripts). Entity component system (ECS) engines such as Unity's DOTS and Bevy go further: an entity is an id, components are plain data, and systems run over every entity that has a given set of components. |
| Kotlin, C#, Java | Kotlin classes are final unless marked open; C# has sealed and Java has final and, since Java 17, sealed classes. All are ways to make inheritance something a class opts into. |
Composition vs inheritance vs mixins/traits
Many languages offer a third tool between the two: mixins or traits, bundles of methods that several unrelated classes can include. Python uses multiple inheritance for mixins, Ruby includes modules, Scala, PHP and Rust have traits, and Java 8 added default methods to interfaces.
| Inheritance | Composition | Mixins / traits | |
|---|---|---|---|
| Relationship | Is-a | Has-a, uses-a | Can-do (adds a capability) |
| Bound | When the class is written | When the object is built, changeable at runtime | When the class is written |
| Sources of reuse | One superclass in most languages | Any number of parts | Several mixins per class |
| Sees internals? | Yes: protected members and call order | No: only the part's public interface | Often yes: mixin code runs on the host's self/this |
| Name clashes | Overriding, by design | None: each part has its own namespace | Resolved by language rules (Python's method resolution order, Scala's trait linearization) or explicitly (PHP insteadof) |
| Class per combination? | Yes, with copied code | No: combinations are built at runtime | Yes, but without copied code: class FlySwimHero(FlyMixin, SwimMixin, Hero) |
| Typical use | Exceptions, frameworks, template method | Varying or combinable behavior, strategies, decorators | Small reusable helpers: comparison, serialization, logging |
Implementation
The visualizer's composition scenario as a complete program: an Ability interface, three parts, and a Hero that delegates to whatever parts it holds. Parts are added and removed at runtime, and climbing is added as one new class. In C++ the hero owns its parts through std::unique_ptr.
from abc import ABC, abstractmethod
from collections.abc import Iterable
class Ability(ABC):
@abstractmethod
def move(self, who: str) -> str: ...
class Fly(Ability):
def move(self, who: str) -> str:
return f"{who} flies"
class Swim(Ability):
def move(self, who: str) -> str:
return f"{who} swims"
# The change request: one new part. Nothing else is edited.
class Climb(Ability):
def move(self, who: str) -> str:
return f"{who} climbs"
class Hero:
"""Has abilities (composition) instead of being a kind of hero."""
def __init__(
self, name: str, abilities: Iterable[Ability] = ()
) -> None:
self._name = name
self._abilities: list[Ability] = list(abilities)
def gain(self, ability: Ability) -> None:
self._abilities.append(ability)
def lose(self, ability: Ability) -> None:
self._abilities = [a for a in self._abilities if a is not ability]
def moves(self) -> list[str]:
# Delegation: Hero has no movement code of its own.
return [a.move(self._name) for a in self._abilities]
if __name__ == "__main__":
fly = Fly()
kai = Hero("Kai", [fly])
print(kai.moves()) # ['Kai flies']
kai.gain(Swim()) # power-up
print(kai.moves()) # ['Kai flies', 'Kai swims']
kai.lose(fly) # wings break
print(kai.moves()) # ['Kai swims']
kai.gain(Climb())
print(kai.moves()) # ['Kai swims', 'Kai climbs']Key takeaways
- Inheritance reuses code through an is-a relationship fixed in the class declaration; composition reuses it through has-a fields and delegation, decided when the object is built and changeable at runtime.
- When features combine, inheritance needs a class per combination (2ⁿ − 1 for n on/off features, a × b for two independent dimensions); composition needs one part per feature (n, or a + b).
- In the visualizer's "Add climbing" request, inheritance adds 4 classes and copies the climbing code 4 times; composition adds 1 class. Neither edits an existing class: the cost of inheritance is multiplication, duplication and rigidity, not edits.
- Inheritance couples a subclass to its parent's internals, which causes fragile base classes; composition depends only on a part's public interface.
- Inherit for a true, Liskov-safe is-a, a template method, or a framework designed for extension. Otherwise, hold the other object in a field.
- Strategy, Decorator and Bridge are all composition: one swappable part, stackable wrappers, and two hierarchies joined by a field.
Common pitfalls
- Subclassing a class just to reuse a few of its methods (
Stack extends Vector): the subclass inherits the whole public interface, including methods that break its rules. Hold the object in a field and expose only what you need. - Overriding methods of a class that was not designed for extension. If the parent calls its own overridable methods internally, your overrides change its behavior in ways nobody documented (the counting set that reports 6 instead of 3).
- Encoding combinations or runtime state as types:
FlySwimHero,PremiumTrialUser. If an object may need to change "what kind" it is, that kind belongs in a field. - Going too far the other way: an interface, a factory and five tiny classes for behavior that has one variant and will not change. Composition adds indirection; spend it where variation is real.
Interview tips
- Quote the principle and justify it: "favor object composition over class inheritance" (Gang of Four), because composition is flexible at runtime, avoids subclass explosion and keeps coupling to public interfaces.
- In LLD rounds, when you catch yourself naming a class after two features (
EmailSmsNotifier), say so out loud and refactor to parts behind an interface. Interviewers look for that moment. - Show balance: name a case where you would inherit (exceptions, template method, a framework base class) and mention the Liskov substitution principle as the test for a safe is-a.
Real-world applications
- Game engines: characters and objects assembled from components (Unity components, ECS in Unity DOTS and Bevy) instead of deep class trees.
- I/O libraries: Java streams and readers wrap each other to add buffering, compression and encoding in any combination.
- UI frameworks: React components are combined through props and children rather than extended.
- Notification, pricing and policy engines: channels, discounts and rules plugged into a service as a list of parts.
- Dependency injection: services receive their collaborators as constructor arguments, which is composition wired by a container.
Test yourself
A hero can have any combination of 4 abilities. With one subclass per combination, how many hero subclasses are needed?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.