Card 05/ 10
All 10 cards
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.
| Compared on | Overriding | Overloading |
|---|---|---|
| Where the two methods live | Parent and subclass | Anywhere, usually one class |
| Name | The same | The same |
| Parameter list | The same | Must differ |
| Decided by | The runtime type of the object | The compiler, from declared types |
| Decided when | While the program runs | While it is compiled |
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 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.