Card 01/ 09
Polymorphism: The Object Chooses Which Method Body Runs
A label method with eight if statements, one per customer type, and the way to delete all eight.
Polymorphism means one method call can run different code depending on the object it is called on. When a subclass overrides a method, the body that runs is chosen by the class of the object, never by the type of the variable holding it, and the choice is made while the program runs.
A method that prints an address label has a chain of eight if statements in it, one per customer type. Adding a ninth type means finding that method, and the four others like it, and hoping there were only five. The alternative is to let the object answer: every customer type declares its own label(), and the calling code calls label() on whatever it is holding.
class Customer {
String name = "Ada";
String label() { return "To: " + name; }
}
class PremiumCustomer extends Customer {
@Override String label() { return "To our valued customer: " + name; }
}
Customer c = new PremiumCustomer();
System.out.println(c.label());To our valued customer: AdaThe variable is a Customer. The object is a PremiumCustomer. The body that ran is the subclass's, and the rule is one sentence: an overridden method is chosen by the type of the object, never by the type of the variable.
This is polymorphism in practice: one call site, several possible bodies, the choice made while the program runs.
So the if chain disappears, and adding a ninth customer type becomes writing one class. Nothing that calls label() has to be found, read or changed, which is the point of the whole mechanism.
← → move through sections and cards