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
Method overriding
1:00Reel
Theory
Read or listen first. About 2 min.
What it is
Method overriding means that a subclass provides its own implementation of a method that it inherits. Name and parameters stay the same. For objects of the subclass the new body replaces the old one, also when the call is made through a variable of the parent type.
Which body runs is decided at run time, by the class of the object. This is called dynamic dispatch, and it is the engine of polymorphism. The type of the variable decides only which calls are allowed.
The subclass may still reach the replaced body with super. So there are two styles: replace the parent's behaviour, or extend it by doing something before or after.
Why it exists
A caller can say chef.make_dish() without asking which chef it is. New kinds of chef arrive as new classes, and the caller stays as it is. That is the open/closed principle at work.
It gives a good default. A child that has nothing special to say inherits the parent's body and writes nothing.
Frameworks live from it. They own the flow, and call methods that you override: a page is requested, a test starts, a screen opens.
A short history
1967
Simula 67 introduces classes, subclasses and virtual procedures: a procedure that a subclass can give a new body.
2011
C++11 adds the words override and final. The compiler can now check that a function really overrides a virtual one.
2021
TypeScript 4.3 (26 May) adds the override keyword and the option noImplicitOverride.
2023
Python 3.12 adds typing.override. PEP 698, created on 5 September 2022, names safe refactoring as a motivation.
Words to know
- Override
- Same name and parameters in a subclass. Chosen at run time by the object.
- Overload
- Same name with different parameters. Chosen by the compiler from the types of the arguments.
- Hide
- A static method or a field with the same name in a subclass. Chosen by the type of the variable, not by the object.
- Static type
- The type of the variable: which calls are allowed.
- Dynamic type
- The class of the object: which body runs.
- Dynamic dispatch
- Finding the body at run time.
- Covariant return
- The override returns a more specific type.
- super
- The next class up. In Python: the next class in the method resolution order.
- Hook
- A method that exists to be overridden. Often empty in the parent.
- Self call
- A method of the object calls another method of the same object. It may land in a subclass.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Inherit. The child starts with the parent's body
Understand it
Start here
Cards with pasted slips
A class prints one card with three lines and gives everybody a copy. Some children paste a paper slip over a line. Whoever holds a card in their hand reads what is on top.
Line: method. Copy: subclass. Slip: override. Envelope: type of the variable.
How it works
One call, four answers
class Chef: def __init__(self, name): self.name = name def make_dish(self): return f"{self.name}: a basic dish"class ItalianChef(Chef): def make_dish(self): return f"{self.name}: pasta"class JapaneseChef(Chef): def make_dish(self): return f"{self.name}: sushi"class MexicanChef(Chef): def make_dish(self): return f"{self.name}: tacos"def dinner(chefs): for chef in chefs: print(chef.make_dish())dinner([ItalianChef("Asha"), JapaneseChef("Noor"), MexicanChef("Max"), Chef("Lee")])Who has a body for makeDish
1/3The parent
Two methods, two bodies. The manager knows this class and no other.
usesextends (is a)
A call through the parent type
Where is the body?
Rules
What a correct override must keep
Six rules (Java), with their reason
| Rule | Because a caller of the parent |
|---|---|
| Same name | calls this name |
| Same parameters: number, types, order | passes these arguments |
| Same or covariant return | uses the result as the parent's type |
| Same or wider access: protected may become public | is allowed to call it |
| Same or fewer checked exceptions | handles only those |
| Use `@Override` | is better served by a compile error than by a silent new method |
The same rules elsewhere
| Language | What is virtual | Mark | Parameters differ? |
|---|---|---|---|
| Java | All, except static, private, final | @Override | It is an overload |
| C++ | Only virtual functions | override | It hides the parent's function |
| C# | Only virtual or abstract | override is required, new hides | It is an overload |
| TypeScript | All methods | override, required with noImplicitOverride | Type error if they do not fit |
| Python | All | @typing.override, checked by type checkers | It overrides anyway, only the name counts |
class Chef: def make_dish(self): return "basic" def serve(self, guests): return f"{self.make_dish()} for {guests}"class Typo(Chef): def make_dich(self): return "pasta" # a new methodclass Other(Chef): def serve(self): return "only for me" # replaces, with other parametersprint(Typo().serve(2)) # basic for 2try: Other().serve(2)except TypeError as error: print("broken:", error)Look-alikes
Override, overload, hide
Three things with the same name
| Override | Overload | Hide | |
|---|---|---|---|
| What | Child replaces a parent's method | Several methods share a name | Child has a static method or field with the parent's name |
| Parameters | Same | Different | Same |
| Where | Parent and child | One class, or parent and child | Parent and child |
| Chosen by | The object, at run time | Argument types, by the compiler | The variable's type, by the compiler |
| Purpose | Change inherited behaviour | Offer alternatives | Usually an accident |
| Return type | Same or covariant | May differ | Own |
functools.singledispatch gives something similar.class Chef { static String shop() { return "market"; } String makeDish() { return "basic"; } String cook() { return "something"; } // overload 1 String cook(String dish) { return dish; } // overload 2 String cook(int portions) { return portions + " x"; } // overload 3}class ItalianChef extends Chef { static String shop() { return "bakery"; } // hides @Override String makeDish() { return "pasta"; } // overrides}// Chef c = new ItalianChef();// c.makeDish() "pasta" the object decides// c.cook("soup") "soup" the compiler chose overload 2// Chef.shop() "market" no object is asked// ItalianChef.shop() "bakery"Closed doors
What cannot be overridden
final methods
The parent locked them. Sometimes for safety, sometimes because other methods rely on them.
static methods
They belong to the class. The same name in a child hides. See Static methods and fields.
private methods
The child cannot see them. The same name is simply another method.
constructors
Not inherited in Java. They call the parent's, they do not replace it.
Non-virtual C++ functions
Without virtual the variable's type decides.
How to lock a method or a whole class, and when that is wise, is told in Preventing subclassing.
Both bodies
Replace or extend: super
class Chef: def make_dish(self): return ["plate", "basic dish"]class Replace(Chef): def make_dish(self): return ["pasta"]class After(Chef): def make_dish(self): return super().make_dish() + ["pasta"]class Before(Chef): def make_dish(self): return ["starter"] + super().make_dish()for cls in (Replace, After, Before): print(cls.__name__, cls().make_dish())Writing Chef.make_dish(self) instead of super().make_dish() also works here. It stops working well with several parents, because it names one class and skips the others. See The diamond problem.
More specific
Covariant return types
A parent returns Dish. A child may promise PastaDish. Callers of the parent still get a dish. Callers who know the child get more, without a cast. Parameters go the other way: a child may accept more, never less. Java does not use this for parameters: another parameter type is an overload. All of it is in Covariance and contravariance.
class Dish { String name() { return "dish"; } }class PastaDish extends Dish { int minutes() { return 9; } }class Chef { Dish plate() { return new Dish(); } }class ItalianChef extends Chef { @Override PastaDish plate() { return new PastaDish(); }}// int m = new ItalianChef().plate().minutes(); no castEvery child must do the parent's clean-up as well. How do you make sure?
BreaksAsk them to call super
- How
- A comment: always call
super().close()last. - Limit
- One of twenty children forgets it, and nothing tells you.
- Choose when
- Only with a check, as Android does with its @CallSuper lint.
WorksRepeat the clean-up
- How
- Each child copies the lines.
- Limit
- Twenty copies, and the parent's change reaches none.
- Choose when
- Never for long.
StrongA fixed method and a hook
- How
close()is final in the parent: it does its work and callson_close(), which is empty by default.- Limit
- Children can only act at the places that you planned.
- Choose when
- Nearly always.
Override when
- The child is a true special case of the parent
- Callers must not notice which one they have
- The method was made to be overridden
- You keep every promise of the parent
Choose something else when
- You only want to reuse a few lines: hold an object
- The child would throw or do nothing
- You need to change behaviour while running: Strategy
- You do not know who calls the method inside the parent
Summary
The whole topic in one minute.
Overriding: same name, same parameters, a new body in the subclass. The variable decides what may be called, the object decides what runs.
Keep the parent's promise: accept at least as much, return something that fits, throw nothing new, be at least as visible. Mark it with @Override or override, so that a typo becomes an error.
Be careful with self calls, with constructors that call overridable methods, and with rules such as always call super. A fixed public method with small hooks is usually safer.
- Same name, same parameters, new body in the child.
- The variable decides what may be called, the object decides what runs.
- Overloads are chosen by the compiler, static methods and fields are hidden.
- Return may be narrower, access wider, checked exceptions fewer.
- Mark every override, so that a typo is an error.
- super reaches the replaced body. If everybody must call it, use a hook instead.