AlgoViz

Method overriding

medium 45 min

A subclass gives its own body to a method that the parent already has.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:42

See it run

Follow one call: who allows it, who answers it, and when it comes back down.

Operations

One call, many dishes

The manager knows Chef and asks four objects.

Step 1 of 5

Four objects

managerknows ChefdishesnoneashaItalianChefown bodyyesnoorJapaneseChefown bodyyesmaxMexicanChefown bodyyesleeChefown bodythe default

The variable chef can hold all of them. It allows one call: make_dish.

Step 1: Four objects

class Chef:    def make_dish(self): return "basic dish"class ItalianChef(Chef):    def make_dish(self): return "pasta"class JapaneseChef(Chef):    def make_dish(self): return "sushi"class MexicanChef(Chef):    def make_dish(self): return "tacos"for chef in [asha, noor, max_, lee]:    print(chef.make_dish())
Good for
Kinds that grow
Costs
One lookup per call
Questions about the kind
0

Point at the one line that calls, then at the class that answers.

In the real world

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

Nobody calls super, and the job is always closed.

Step 1 of 5

Run

appcallerJob partrun is finallogopenImport parthooksworkwaitingrun()

The public method is fixed in the parent.

Step 1: Run

Common mistakes

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

  • Typo without a mark

    major

    A new method is added and the old one still runs.

    Wrong
    String makeDich() { return "pasta"; }
    Right
    @Override String makeDish() { return "pasta"; }
  • self instead of super

    critical

    The method calls itself without end.

    Wrong
    def make_dish(self):    return self.make_dish() + " + mint"
    Right
    def make_dish(self):    return super().make_dish() + " + mint"
  • An override that refuses

    major

    Callers of the parent do not expect an error.

    Wrong
    def save(self, data):    raise NotImplementedError
    Right
    class ReadOnlySource:      # no save at all    def load(self): ...
  • equals without hashCode

    critical

    Equal objects end in different buckets.

    Wrong
    @Override public boolean equals(Object o) { ... }// no hashCode
    Right
    @Override public boolean equals(Object o) { ... }@Override public int hashCode() { ... }
  • Static called through an object

    minor

    It looks like dispatch and is not.

    Wrong
    chef.shop();     // variable's type decides
    Right
    Chef.shop();

Interview tips

  • Two columns

    • Variable: may I call it?
    • Object: who answers?
    • Say both
  • Three words

    • Fixed
    • Default
    • Required
  • Four checks

    • Inputs
    • Results
    • Errors
    • Cost
  • Not super

    • Fixed public method
    • Small hooks
    • Nothing to forget