Inheritance vs composition
medium 40 minTwo ways to reuse code.
Watch lesson4:52
Where it shows up
The same pattern appears across everyday software.
Java `Stack`
It extends `Vector`, so a stack also has insert by index. The documentation says the `Deque` interface should be used in preference.
Java `Properties`
It inherits from `Hashtable`. The documentation strongly discourages `put` and `putAll`, because they let callers insert entries that are not strings. An inherited method too many.
Java `FilterInputStream`
Wraps some other input stream as its source of data, so buffering, unzipping and others can be stacked. It is composition, with a small parent for the forwards.
Guava `ForwardingSet`
Forwards all its calls to another set. Its page warns that overriding `add` alone does not change `addAll`, and offers `standardAddAll`.
Kotlin
Classes are final by default. The `by` clause delegates an interface to an object. The documentation calls delegation a good alternative to implementation inheritance.
Go
No type inheritance. Effective Go describes embedding: a struct borrows pieces of an implementation from the types inside it.
React
Its legacy documentation recommends composition, and says that at Facebook they found no use case for component inheritance hierarchies in thousands of components.
Unity
A GameObject acts as a container for components, which decide how it looks and what it does.
Python `UserDict`
A wrapper around a dictionary object for easier subclassing. The real dictionary is reachable as an attribute, and calls go through the class's own methods.