AlgoViz

Multiple parents in single inheritance

medium 45 min

Java, C#, Kotlin, Swift and TypeScript allow one parent class.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:35

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

  1. 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.

  2. 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.

  3. 2019

    C# 8 (September) adds default interface members, for the same reason.

  4. 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.

Step 1 of 4

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.

Pip and the jobs on the beach

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

«abstract»Bird+ display()SwimmingBird+ swim()FlyingBird+ fly()PenguinSparrow

1/3One ability each

Penguins swim, sparrows fly. Two classes between, and it still looks tidy.

extends (is a)

The abilities are independent of each other. A tree cannot show independent things, because it has only one way down.

Good: one parent, roles and parts

«abstract»Bird# name: String+ display()Duck+ setFlyBehavior(b)

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

ToolTypeBehaviourStateGoodPrice
Parent classyesyesyesEverything at onceOnly one, and for life
InterfaceyesnonoClear contract, checked by the compilerEach class writes each method
Default methodyesyesnoWorking steps for freeTwo defaults can conflict
CompositionnoyesyesFlexible, can change at run timeForwarding lines
MixindependsyesoftenReusable slice of classDepends on the language, order matters
Interface plus part is the usual pair: the interface gives the type, and the part gives the behaviour.

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 default has no fields. All state stays in the one class and its parts. That is why two interfaces can never bring two copies of a field.

The same duck on two days

An object cannot change its parent class. It can change a part.

Languages

The same wish in eight languages

LanguageParent classesType from manyBehaviour from many
Java1implements A, BDefault methods (8 and later)
C#1: Base, IA, IBDefault interface members (8 and later)
Kotlin1: Base(), A, BInterface bodies, and delegation with by
Swift1ProtocolsProtocol extensions
TypeScript1implements A, BHelper functions, mixin functions
PHP1InterfacesTraits
GononeInterfaces, kept by having the methodsEmbedding
Python, C++manyAbstract classes, Python protocolsAllowed directly: see Multiple inheritance
Python
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 checked
Structural typing in Python. No parent is named. The run time check looks at method names only, not at parameters.
Edit and run it in your browser
TypeScript
type 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 flies
Mixin functions in TypeScript: a function that takes a class and returns a larger one. The result is still one chain of single parents.

Judgement

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, MusicPlayer with 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