Card 05/ 10

ComparisonDifficulty: Intermediate1 min

Overriding Replaces a Body; Overloading Adds a Second One

Two words a letter apart, describing two mechanisms that are resolved at different times by different parts of the system. Confusing them produces a method that is never called and no error to say so.

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.