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

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

  1. 1967

    Simula 67 introduces classes, subclasses and virtual procedures: a procedure that a subclass can give a new body.

  2. 2011

    C++11 adds the words override and final. The compiler can now check that a function really overrides a virtual one.

  3. 2021

    TypeScript 4.3 (26 May) adds the override keyword and the option noImplicitOverride.

  4. 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.

Step 1 of 4

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.

The good luck cards
HelloGood luckYour class

Line: method. Copy: subclass. Slip: override. Envelope: type of the variable.

How it works

One call, four answers

Python
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")])
The function knows Chef only. Lee has no override and uses the parent's body.
Edit and run it in your browser

Who has a body for makeDish

Manager+ evening(chefs)Chef# name: String+ makeDish()+ washHands()

1/3The parent

Two methods, two bodies. The manager knows this class and no other.

usesextends (is a)

Adding a fourth kind is a new box with one arrow. The manager does not change.

A call through the parent type

Same object, two calls. One is answered by the child, one by the parent.

Where is the body?

The meaning of dispatch. Python walks like this along the method resolution order and caches the result. Java and C++ usually prepare a table per class, so that nothing is searched. See Polymorphism internals.

Rules

What a correct override must keep

Six rules (Java), with their reason

RuleBecause a caller of the parent
Same namecalls this name
Same parameters: number, types, orderpasses these arguments
Same or covariant returnuses the result as the parent's type
Same or wider access: protected may become publicis allowed to call it
Same or fewer checked exceptionshandles only those
Use `@Override`is better served by a compile error than by a silent new method
The first five are the compiler's version of one idea: the child must be usable wherever the parent is. The full idea, with meaning included, is the Liskov substitution principle.

The same rules elsewhere

LanguageWhat is virtualMarkParameters differ?
JavaAll, except static, private, final@OverrideIt is an overload
C++Only virtual functionsoverrideIt hides the parent's function
C#Only virtual or abstractoverride is required, new hidesIt is an overload
TypeScriptAll methodsoverride, required with noImplicitOverrideType error if they do not fit
PythonAll@typing.override, checked by type checkersIt overrides anyway, only the name counts
Python
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)
In Python only the name counts. A typo adds a method, and other parameters break the callers of the parent.
Edit and run it in your browser

Look-alikes

Override, overload, hide

Three things with the same name

OverrideOverloadHide
WhatChild replaces a parent's methodSeveral methods share a nameChild has a static method or field with the parent's name
ParametersSameDifferentSame
WhereParent and childOne class, or parent and childParent and child
Chosen byThe object, at run timeArgument types, by the compilerThe variable's type, by the compiler
PurposeChange inherited behaviourOffer alternativesUsually an accident
Return typeSame or covariantMay differOwn
Python has no overloading by type: the last definition of a name wins. functools.singledispatch gives something similar.
Java
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"
All three in one class. The comments say who decides.

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

Python
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())
Three styles. In the last one the order matters.
Edit and run it in your browser

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.

Java
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 cast
The return type gets more specific, and the call needs no cast.

Every 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 calls on_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.

Sources