Card 02/ 10

ExampleDifficulty: Intermediate1 min

A PremiumCustomer That Is Already a Customer

Two classes, four lines between them, and a method that was never written twice.

java
class Customer {
    String name;
    String label() { return "To: " + name; }
}

class PremiumCustomer extends Customer {
    double discountRate;
}
java
PremiumCustomer p = new PremiumCustomer();
p.name = "Ada";
p.discountRate = 0.15;

System.out.println(p.label());

Customer asCustomer = p;
System.out.println(asCustomer.label());
text
To: Ada
To: Ada

p.label() works although PremiumCustomer declares no such method — it is part of the class because Customer declares it. p.name works for the same reason.

Line 7 is the one to notice. Assigning a PremiumCustomer to a Customer variable needs no cast and loses nothing: there is one object, and it genuinely is a customer. What the narrower variable loses is reach — asCustomer.discountRate will not compile, because the declared type has no such field.