Card 05/ 10

ComparisonDifficulty: Intermediate1 min

Overriding vs Overloading

Two words a letter apart, decided at different times, and a method that is never called if you confuse them.

Overriding is a subclass replacing a parent method's body with a method of the same name and the same parameter list; which body runs is decided by the object while the program runs. Overloading is adding another method with the same name and a different parameter list; the compiler picks between them.

Overriding against overloading, on where, what and when
Compared onOverridingOverloading
Where the two methods liveParent and subclassAnywhere, usually one class
NameThe sameThe same
Parameter listThe sameMust differ
Decided byThe runtime type of the objectThe compiler, from declared types
Decided whenWhile the program runsWhile it is compiled
java
class Customer {
    String label() { return "To: " + name; }
}

class PremiumCustomer extends Customer {
    @Override
    String label() { return "To our valued customer: " + name; }

    String label(String prefix) { return prefix + name; }
}
line 7 overrides; line 9 overloads

Line 9 does not replace anything. It is a second method with the same name and a different parameter list, so a PremiumCustomer now has two label methods and the compiler picks between them by what you pass.

The decision rule. Write @Override on every method you intend to override. It is not decoration: the compiler checks that something up the hierarchy really has that exact signature, and it fails the build when a typo or a changed parameter type has quietly turned an override into an overload.