All topics
library
intermediate

Composition over Inheritance

Know why delegation through composition is usually better than extending a class.

Composition over inheritance favors assembling objects with needed behavior (has-a) over extending classes (is-a). Advocated in Effective Java Item 18.

Inheritance = born into a family (can't choose parents). Composition = hiring specialists (choose and swap anytime).

Key Concepts

1
Why composition wins: 1. Flexibility: swap composed objects at runtime. Inheritance is fixed at compile time. 2. Encapsulation: inheritance breaks it — subclasses depend on superclass internals. If superclass changes, subclasses break (fragile base class problem). 3. Testing: composed objects can be mocked independently. 4. Multiple behaviors: compose many objects, but extend only one class.
2
The classic mistake: Properties extends Hashtable in the JDK. Properties is-not-a Hashtable; it merely uses one. This exposes put(Object, Object) that violates Properties' String-only contract.
3
When inheritance is right: genuine is-a relationship AND superclass designed for extension (documented, stable API). Template Method pattern is valid inheritance.
4
Delegation pattern: hold a reference to the inner object, forward method calls, optionally add behavior before/after.