Card 02/ 10

ExampleDifficulty: Intermediate1 min

Inheritance Example: A PremiumCustomer That Is Already a Customer

Two classes, a label method written once, and a subclass object held in a parent-type variable.

With inheritance (extends), a subclass object can call every method its parent class declares, and can be stored in a variable of the parent's type with no cast, the bracketed type that forces a conversion. Two classes 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.