Interface vs abstract class
medium 45 minAn interface says what something can do and leaves the how to others.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
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
majorEvery child must refuse what it cannot do, at run time.
Wrongclass Vehicle: def fly(self): raise NotImplementedErrorRightclass Flyable(ABC): @abstractmethod def fly(self): ...Forgot the parent constructor
criticalPython does not call it for you. The fields are missing later.
Wrongclass Car(Vehicle): def __init__(self): self.doors = 4Rightclass Car(Vehicle): def __init__(self): super().__init__("car", 200)Hole called in the constructor
criticalThe child is not ready.
Wrongdef __init__(self): self.header = self.make_header()Right@propertydef header(self): return self.make_header()Base class as parameter type
minorWrappers and fakes must inherit things they do not need.
Wrongdef copy(a: BaseStorage, b: BaseStorage): ...Rightdef copy(a: Storage, b: Storage): ...Dishonest default
majorIt compiles everywhere and fails somewhere.
Wrongdefault void delete(String k) { throw new UnsupportedOperationException(); }Rightinterface 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