AlgoViz

Interface vs abstract class

medium 45 min

An interface says what something can do and leaves the how to others.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:42

See it run

Objects at run time: which part comes from the base, which promise the caller holds, and what breaks when a promise grows.

Operations

Create a sea plane

The base cannot be created, but its constructor runs.

Step 1 of 5

Try the base

appmainVehicleabstract classholeskindfinishedstart, labelVehicle('ghost', 10)TypeError

Vehicle still has a hole, so Python refuses it with a TypeError.

Step 1: Try the base

class Vehicle(ABC):    def __init__(self, name, max_speed):        if max_speed <= 0: raise ValueError        self.name, self.max_speed = name, max_speed        self._running = False    @abstractmethod    def kind(self): ...class SeaPlane(Vehicle, Flyable):    def __init__(self, name):        super().__init__(name, 350)    def kind(self): return "air, water"Vehicle("ghost", 10)heron = SeaPlane("Heron")heron.label()
Good for
Shared state and checks
Costs
The one parent
Checks of the speed
1, in the base

Say which lines run for every child, and which only for this one.

In the real world

The same interface vs abstract class doing real jobs. Pick one and step through it.

The parade as objects: one promise, three classes, and a promise that grows.

Step 1 of 6

The board

light groupasks for GlowspromiseglowwhaleWagon, GlowslampoffbicycleGlowswheel lightofflanternGlowscandleoff

The group asks for one thing: glow.

Step 1: The board

Common mistakes

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

  • Abilities in the parent

    major

    Every child must refuse what it cannot do, at run time.

    Wrong
    class Vehicle:    def fly(self): raise NotImplementedError
    Right
    class Flyable(ABC):    @abstractmethod    def fly(self): ...
  • Forgot the parent constructor

    critical

    Python does not call it for you. The fields are missing later.

    Wrong
    class Car(Vehicle):    def __init__(self): self.doors = 4
    Right
    class Car(Vehicle):    def __init__(self):        super().__init__("car", 200)
  • Hole called in the constructor

    critical

    The child is not ready.

    Wrong
    def __init__(self):    self.header = self.make_header()
    Right
    @propertydef header(self): return self.make_header()
  • Base class as parameter type

    minor

    Wrappers and fakes must inherit things they do not need.

    Wrong
    def copy(a: BaseStorage, b: BaseStorage): ...
    Right
    def copy(a: Storage, b: Storage): ...
  • Dishonest default

    major

    It compiles everywhere and fails somewhere.

    Wrong
    default void delete(String k) {    throw new UnsupportedOperationException(); }
    Right
    interface DeletableStorage extends Storage {    void delete(String k); }

Interview tips

  • Start at the caller

    • Which calls are needed?
    • That is the interface
    • No more than that
  • Ask about memory

    • Must shared code remember?
    • Yes: a class
    • No: a default may do
  • Final steps, small holes

    • Public method is fixed
    • Protected hole varies
    • Two different names
  • Growing

    • Honest default
    • Or a second interface
    • Contract tests for all