Card 01/ 09

ConceptDifficulty: Intermediate1 min

One Call, Several Bodies, and the Rule That Picks One

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(), the calling code calls label() on whatever it is holding, and nothing in the calling code names a type at all.

java
class Customer { 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());
text
To our valued customer: Ada

The 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.

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.