Card 01/ 10
All 10 cards
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.
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.
| Declared in the parent | In the subclass? |
|---|---|
public and protected fields and methods | Yes, and reachable |
| Package-private members, same package | Yes, and reachable |
private fields and methods | Part of the object, not reachable by name |
| Constructors | No — each class writes its own |
static methods | Reachable, 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".