Overloading, Overriding and Binding
Overloaded methods share a name with different parameters and are chosen at compile time from declared types, while overridden methods are chosen at run time from the actual object.
Distinguish compile-time overload selection from runtime method dispatch.
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.