Overloading, Overriding and Binding
Brew Bar's receipt calls label() on every drink, but iced drinks should say how much ice they have. Separately, the till wants addToOrder to accept either one drink or a drink plus a quantity. Both situations reuse a method name, yet Java treats them in completely different ways, at completely different moments.
The rule
Overloading picks by declared types at compile time; overriding picks by the real object at run time.
Overloading means several methods in one class share a name but have different parameter lists:
void addToOrder(Drink d) { addToOrder(d, 1); }
void addToOrder(Drink d, int qty) { /* ... */ }The compiler chooses which one to call by looking at the argument types as they are declared in your code. This early choice is called static binding. Changing only the return type does not count as an overload and will not compile.
Overriding means a subclass supplies its own version of an inherited method with the same name and parameters:
public class IcedDrink extends Drink {
private int iceGrams;
// constructor as before
@Override
public String label() {
return super.label() + " with " + iceGrams + "g ice";
}
}At run time the JVM looks at the actual object and runs that class's version. This late choice is dynamic binding, and it is what lets one loop treat every drink the same way while each prints correctly:
Drink d = new IcedDrink("Iced latte", 330, 80);
System.out.println(d.label()); // Iced latte (330c) with 80g iceTwo helpers: @Override asks the compiler to confirm you really are overriding something, catching typos such as lable(). And super.label() calls the parent's version from inside the override.
Static, private and final methods are never overridden, so they are always bound at compile time.
The shortcut
For any call, ask: "Same class, different parameters?" That is overloading: look at the declared type of the argument. "Subclass, same parameters?" That is overriding: look at the real object after new.
Find the declared type
Drink dis declared as a Drink, so the compiler checks that Drink has alabel()method. It does.
Drills
Answer fast — trust the rule.
Drink's describe() returns "drink"; IcedDrink overrides it to return "iced drink". What does Drink d = new IcedDrink(...); System.out.println(d.describe()); print?
A class has static String tag(Drink d) returning "drink" and static String tag(IcedDrink d) returning "iced". What does Drink d = new IcedDrink(...); System.out.println(tag(d)); print?
Which pair of methods in one class does NOT compile?
In IcedDrink you write @Override public String lable(). What happens?
Remember
- Overloading: same class, different parameters, chosen at compile time by declared types.
- Overriding: subclass, same parameters, chosen at run time by the real object.
- Traps: return-type-only "overloads", and expecting overloads to follow the real object.
