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
See it run
One parent, many roles: who asks for what, and who answers.
Operations
One object, many types
Three callers ask for three types. Which objects may they get?
Step 1 of 6
Two objects
Both are birds. Donald can swim and fly, Bubbles can only float.
Step 1: Two objects
class Duck(Bird, Swimmable, Flyable): ...class RubberDuck(Bird, Swimmable): ...def cross(s: Swimmable): return s.swim()def show(f: Flyable): return f.soar()def draw(b: Bird): return b.display()- Good for
- Fixed abilities
- Costs
- One small interface each
- Type questions in callers
- 0
Draw the callers first. They tell you which roles exist.
In the real world
The same multiple parents in single inheritance doing real jobs. Pick one and step through it.
Is, can, has: one thing with one parent, three roles and two parts.
Step 1 of 6
It is a phone
The parent class is the one thing it stays for life.
Step 1: It is a phone
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A role that throws
criticalThe compiler accepts the object, the customer finds the error.
Wrongclass RubberDuck(Bird, Flyable): def fly(self): raise NotImplementedErrorRightclass RubberDuck(Bird, Swimmable): def swim(self): return "floats"Parent slot for a helper
majorThe class can never have a real parent again.
Wrongclass Order(Auditable): ...Rightclass Order: def __init__(self, audit): self._audit = auditOverride, then delegate
criticalThe inner object never calls your override.
Wrongclass Loud: def play_note(self, n): ... # never called def play(self): return self._inner.play()RightSong(notes, play_note=loud_note).play()Two truths
majorEach part keeps its own copy of shared state.
WrongPhoneCamera(percent=20); PhonePlayer(percent=20)Rightbattery = Battery(20)PhoneCamera(battery); PhonePlayer(battery)A class for each combination
minorIndependent abilities do not fit into a tree.
Wrongclass FlyingSwimmingBird(Bird): ...Rightclass Duck(Bird, Swimmable, Flyable): ...
Interview tips
Is, can, has
- Is: the one parent
- Can: small interfaces
- Has: parts
Callers first
- Draw who asks
- Give each the smallest role
- No role without a caller
Know the traps
- Conflicting defaults
- Shared method names
- The self problem
Say the price
- Forwarding lines
- Run time checks for lookups
- One more object