Method overriding
medium 45 minA subclass gives its own body to a method that the parent already has.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
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
majorA new method is added and the old one still runs.
WrongString makeDich() { return "pasta"; }Right@Override String makeDish() { return "pasta"; }self instead of super
criticalThe method calls itself without end.
Wrongdef make_dish(self): return self.make_dish() + " + mint"Rightdef make_dish(self): return super().make_dish() + " + mint"An override that refuses
majorCallers of the parent do not expect an error.
Wrongdef save(self, data): raise NotImplementedErrorRightclass ReadOnlySource: # no save at all def load(self): ...equals without hashCode
criticalEqual objects end in different buckets.
Wrong@Override public boolean equals(Object o) { ... }// no hashCodeRight@Override public boolean equals(Object o) { ... }@Override public int hashCode() { ... }Static called through an object
minorIt looks like dispatch and is not.
Wrongchef.shop(); // variable's type decidesRightChef.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