AlgoViz

Polymorphism

medium 45 min

One call, many behaviours: the caller asks for the same thing, and the object that receives the call decides how it is done.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:47

See it run

Follow one call: who may be asked, who is asked, and which version runs.

Operations

The type switch

Three functions ask the same question. A podcast arrives.

Step 1 of 5

Two kinds

playerlabel(item)cases2statisticsminutes(item)cases2sharelink(item)cases2kindsKindvalues2

Songs and radio. Three functions switch on the kind, and all agree.

Step 1: Two kinds

def minutes(item):    if item.kind == "song":        return item.seconds // 60    elif item.kind == "podcast":        return item.seconds // 60    return 0
Good for
One place, fixed kinds
Costs
Each kind edits every copy
Places for a new kind
3

End a chain with an error, never with a quiet default.

In the real world

The same polymorphism doing real jobs. Pick one and step through it.

The same signal reaches three devices.

Step 1 of 4

A button

remoteone buttonsendspowertelevisionDeviceshowsnothingdisc playerDeviceplaysnothingconsoleDevicestartsnothing

The remote sends one signal: power.

Step 1: A button

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A subclass for a number

    minor

    Only the value differs, so no behaviour is overridden.

    Wrong
    class PremiumCustomer(Customer):    def percent(self): return 20
    Right
    Customer(name, percent=20)
  • Overload instead of override

    critical

    Collections call equals(Object). The new method is never used.

    Wrong
    public boolean equals(Point p) { ... }
    Right
    @Overridepublic boolean equals(Object o) { ... }
  • Asking for the class after the call

    major

    The contract lacks something, and the next kind is an edit here.

    Wrong
    if isinstance(item, Podcast):    at = item.position
    Right
    if isinstance(item, Resumable):    at = item.resume_at()
  • A kind that cannot keep the contract

    critical

    Every loop now needs a special case.

    Wrong
    class LiveRadio:    def minutes(self): raise NotImplementedError
    Right
    def minutes(self): return None   # allowed by the contract
  • Work in the parent's constructor

    major

    The child's version runs before the child's fields exist.

    Wrong
    def __init__(self):    self.text = self.render()
    Right
    def text(self):    return self.render()

Interview tips

  • Two questions

    • May I call it? Static type
    • Which version? Dynamic type
    • Which overload? Declared arguments
  • Contract first

    • Write it from the caller's side
    • Admit unknown in the type
    • Split abilities off
  • What grows?

    • Kinds: methods
    • Operations: switch or visitor
    • Values: a field
  • Review

    • Override markers everywhere
    • No quiet default
    • One table for tags