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

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

pondasks Swimmableair showasks Flyablealbumasks BirddonaldDuckis aBirdcanswim, flybubblesRubberDuckis aBirdcanswim

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

smartphoneextends Phoneis aPhoneroles0parts0

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

    critical

    The compiler accepts the object, the customer finds the error.

    Wrong
    class RubberDuck(Bird, Flyable):    def fly(self): raise NotImplementedError
    Right
    class RubberDuck(Bird, Swimmable):    def swim(self): return "floats"
  • Parent slot for a helper

    major

    The class can never have a real parent again.

    Wrong
    class Order(Auditable): ...
    Right
    class Order:    def __init__(self, audit): self._audit = audit
  • Override, then delegate

    critical

    The inner object never calls your override.

    Wrong
    class Loud:    def play_note(self, n): ...   # never called    def play(self): return self._inner.play()
    Right
    Song(notes, play_note=loud_note).play()
  • Two truths

    major

    Each part keeps its own copy of shared state.

    Wrong
    PhoneCamera(percent=20); PhonePlayer(percent=20)
    Right
    battery = Battery(20)PhoneCamera(battery); PhonePlayer(battery)
  • A class for each combination

    minor

    Independent abilities do not fit into a tree.

    Wrong
    class FlyingSwimmingBird(Bird): ...
    Right
    class 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