Overloading vs Overriding
Why the object decides an override, while the variable decides an overload.
Open this lesson in the learning hubKey points
- Overriding: same name, same parameters, subclass wins. Java picks it at runtime from the real object.
- Overloading: same name, different parameters. Java picks it at compile time from the declared types.
- So
Animal pet = new Cat()gives you the Catspeak()but the Animal overload ofdescribe(). - The compiler chooses the most specific overload that fits. A cast changes the declared type, so it changes the choice.
@Overrideonly compiles on a real override. If you meant to override but changed a parameter, it says so.- Overloading across a supertype and its subtype reads as magic in review. Rename one of the methods instead.
Example
public class Main {
static class Animal {
String speak() { return "generic noise"; }
}
static class Cat extends Animal {
@Override String speak() { return "meow"; } // OVERRIDE: chosen at runtime
}
// OVERLOAD: same name, different parameters, chosen at COMPILE time.
static String describe(Object o) { return "Object overload"; }
static String describe(Animal a) { return "Animal overload"; }
static String describe(Cat c) { return "Cat overload"; }
public static void main(String[] args) {
Animal pet = new Cat();
System.out.println("override -> " + pet.speak()); // meow: the object decides
System.out.println("overload -> " + describe(pet)); // Animal: the variable decides
Cat cat = new Cat();
System.out.println("overload -> " + describe(cat)); // Cat overload
System.out.println("overload -> " + describe((Object) cat)); // Object overload
}
}
Overriding follows the object; overloading follows the variable.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.