Multiple parents in single inheritance
medium 45 minJava, C#, Kotlin, Swift and TypeScript allow one parent class.
Video lesson · Chapter 1 of 6
Make a prediction
Multiple parents in single inheritance
1:03Reel
Theory
Read or listen first. About 2 min.
What it is
In a single inheritance language a class may extend one class only. A duck is a bird, so the one place is taken. It must also be usable where something that swims is asked for, and where something that flies is asked for.
The word inheritance hides three different wishes. Type: other code may treat the duck as a swimmer. Behaviour: the duck gets working methods without writing them again. State: the duck gets fields. A parent class gives all three. The other tools give them one at a time, and that is why they are safer.
So the question is never how to fake a second parent. The question is which of the three you need this time. Interfaces give type, default methods and mixins give type with behaviour, and parts (composition) give behaviour with state.
Why it exists
Without these tools people copy code or build a class for each combination. Two abilities need three extra classes, and four abilities need up to fifteen. The tree grows although no new idea was added.
With them the caller asks for a small role. crossThePond needs swimmers and accepts a duck, a rubber duck and an otter. It does not care about the rest of the object.
And parts can be exchanged while the program runs. A parent class cannot: an object keeps its class for life in these languages.
A short history
1996
JDK 1.0 (23 January). The Java language white paper says that multiple inheritance was discarded and that its desirable features are provided by interfaces, similar to Objective-C protocols.
2014
Java 8 (18 March) gives interfaces default methods, so that old interfaces such as Collection can grow without breaking every class that implements them.
2019
C# 8 (September) adds default interface members, for the same reason.
2019
Python 3.8 ships PEP 544: a Protocol is kept by any class that has the right methods, without naming it as a parent.
Words to know
- Single inheritance
- A class extends at most one class.
- Role interface
- A small interface named after one ability, such as Swimmable.
- Default method
- An interface method with a body. Classes get it free and may replace it.
- Composition
- An object holds another object and uses it.
- Delegation
- Answering a call by passing it to a part.
- Forwarding method
- The one line that passes the call on.
- Mixin
- A piece of class that is added to another class.
- Role object
- An object that plays one role for another object, and can be looked up by role.
- Self problem
- After delegation, the part calls its own methods, never yours.
- Structural type
- A type that is kept by having the right methods, not by naming a parent.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Name what it is. One parent class, for life
Understand it
Start here
A donkey can follow one rope
Pip is a donkey that gives rides on a beach. Pip must learn several jobs, but a donkey with two people pulling goes nowhere. Watch how the jobs reach Pip anyway.
Rope: the parent class. Rosettes: interfaces. Cards: default methods. Bag: composition.
The smell
One class for each combination
The first try uses the only tool in sight: more parent classes. Swimming birds, flying birds, and then birds that do both.
Bad: abilities as parent classes
1/3One ability each
Penguins swim, sparrows fly. Two classes between, and it still looks tidy.
extends (is a)
Good: one parent, roles and parts
1/4What it is
The one parent class carries the name and the duty to show itself.
extends (is a)implementsowns (dies together)has (lives on)
The tools
Four ways to get a second source
What each tool gives
| Tool | Type | Behaviour | State | Good | Price |
|---|---|---|---|---|---|
| Parent class | yes | yes | yes | Everything at once | Only one, and for life |
| Interface | yes | no | no | Clear contract, checked by the compiler | Each class writes each method |
| Default method | yes | yes | no | Working steps for free | Two defaults can conflict |
| Composition | no | yes | yes | Flexible, can change at run time | Forwarding lines |
| Mixin | depends | yes | often | Reusable slice of class | Depends on the language, order matters |
Patterns that use the same tools
Strategy
A family of algorithms behind one contract. The duck has a FlyBehavior and can exchange it. See Strategy.
Mixin
Small focused classes added to another class. TypeScript and Python can do it. See Mixins and traits.
Decorator
Wrap an object to add one ability. Each wrapper adds one. See Decorator.
Role object
Ask the object for a role by its type and get an object that plays it, or nothing.
Which tool this time?
How it works
A default method calls back
A default method knows nothing about the class. It works because it calls the promised methods on the same object. This is a tiny template method.
duck.dive() in Java
The same duck on two days
Languages
The same wish in eight languages
| Language | Parent classes | Type from many | Behaviour from many |
|---|---|---|---|
| Java | 1 | implements A, B | Default methods (8 and later) |
| C# | 1 | : Base, IA, IB | Default interface members (8 and later) |
| Kotlin | 1 | : Base(), A, B | Interface bodies, and delegation with by |
| Swift | 1 | Protocols | Protocol extensions |
| TypeScript | 1 | implements A, B | Helper functions, mixin functions |
| PHP | 1 | Interfaces | Traits |
| Go | none | Interfaces, kept by having the methods | Embedding |
| Python, C++ | many | Abstract classes, Python protocols | Allowed directly: see Multiple inheritance |
from typing import Protocol, runtime_checkable@runtime_checkableclass Swimmable(Protocol): def swim(self) -> None: ...class Otter: # names no parent at all def swim(self) -> None: print("the otter swims")class SwimmingPool: def swim(self, lanes: int, guests: list) -> None: print("a booking, not an animal")print(isinstance(Otter(), Swimmable)) # Trueprint(isinstance(SwimmingPool(), Swimmable)) # True as well: only the name is checkedtype Constructor<T = object> = new (...args: any[]) => T;function Swimming<B extends Constructor>(Base: B) { return class extends Base { swim(): string { return "swims"; } };}function Flying<B extends Constructor>(Base: B) { return class extends Base { fly(): string { return "flies"; } };}class Animal { constructor(public name: string) {} }const Both = Flying(Swimming(Animal));const it = new Both("Creature");console.log(it.name, it.swim(), it.fly()); // Creature swims fliesJudgement
What to write in the interview
A smartphone is a phone, and also a camera, a navigator and a music player. How do you model it?
BreaksA chain of parents
- How
Phone extends MusicPlayer extends Camera.- Limit
- A music player is not a camera. Every change of the camera reaches the phone, and a phone without camera cannot exist.
- Choose when
- Never.
WorksOne class with all interfaces
- How
class Phone implements Camera, Navigator, MusicPlayerwith all code inside.- Limit
- Types are right. The class grows with each ability, and
stop()of the camera and of the player are the same method. - Choose when
- Two or three small roles without shared names.
StrongInterfaces outside, parts inside
- How
- The phone holds a camera part and a player part that share a battery. It forwards, or hands out the part for a role.
- Limit
- More objects, and some forwarding lines.
- Choose when
- Abilities with their own state, or abilities that differ between models.
One parent works when
- The child is the parent for its whole life
- The parent was made to be extended
- Callers need the parent as a type
One parent is wasted when
- It is only there to share a helper method
- It names an ability instead of a kind
- Another wish for the place is already visible
Summary
The whole topic in one minute.
Split the wish: type, behaviour or state. Interfaces, default methods and parts answer them in this order.
Extend one class only where the child truly is the parent for life. Promise abilities with small interfaces. Put what differs or changes into parts.
Watch three traps: defaults that conflict, roles that share a method name, and the self problem of delegation.
- Inheritance is three wishes: type, behaviour, state. Ask which one you need.
- Interface for type, default method for steps, part for behaviour with state.
- Small roles named after abilities; callers ask for the smallest.
- A default uses promised methods only. It has no fields.
- A part changes at run time, a parent does not.
- Never give a role to an object that cannot keep it.
Sources
- Oracle: The Java Language Environment, no more multiple inheritance
- Java tutorial: multiple inheritance of state, implementation and type
- Java tutorial: overriding and default methods
- JEP 126: Lambda expressions and virtual extension methods
- Java SE 21: ArrayList
- Java SE 21: Collection
- Java SE 21: HashSet
- Java version history
- Kotlin: delegation
- C#: update interfaces with default interface methods
- Go: Effective Go, embedding
- Swift: Protocols
- Guava: forwarding decorators
- PHP: traits
- PEP 544: Protocols