Card 01/ 10

ConceptDifficulty: Intermediate1 min

What a Subclass Gets Without Asking

You have a Customer class with a name, an email and a method that formats an address label. Premium customers need all of that, plus a discount rate. Copying the class and adding one field leaves you with two address-label methods to keep in step.

java
class PremiumCustomer extends Customer {
    double discountRate;
}

extends says that a PremiumCustomer is a Customer. Every field and every method declared in Customer is part of a PremiumCustomer too, without a line being copied, and anywhere a Customer is accepted a PremiumCustomer may be handed over.

What crosses the extends boundary and what does not
Declared in the parentIn the subclass?
public and protected fields and methodsYes, and reachable
Package-private members, same packageYes, and reachable
private fields and methodsPart of the object, not reachable by name
ConstructorsNo — each class writes its own
static methodsReachable, but not overridable

The two rows that catch people out are the last three. A private field is still there — every PremiumCustomer has a name in memory — but the subclass cannot write name and reach it. And constructors are not inherited, which is why a subclass with no constructor of its own is not the same as one that borrows the parent's.

So extends buys you one copy of shared behaviour and one place to change it. What it costs is that the subclass is now tied to the parent's decisions, which is why the question to ask before writing it is whether the relationship is really "is a".