Card 01/ 10
Java Inheritance: What extends Gives a Subclass
Premium customers need everything a customer has plus a discount, without a second copy of the class.
class B extends A makes B a subclass of A: every B is an A, and it has every field and method A declares without a line being copied. It does not get A's constructors, and it cannot name A's private members, even though they are part of every B object.
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. extends gives you one:
class PremiumCustomer extends Customer {
double discountRate;
}extends says that a PremiumCustomer is a Customer. Everything declared in Customer is part of a PremiumCustomer too, 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 by name |
| Package-private members, same package | Yes, and reachable by name |
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 rows that catch people out are private and constructors. A private field is still there, since every PremiumCustomer has a name in memory, but the subclass cannot write name and reach it. And constructors are not inherited, so a subclass with no constructor of its own does not borrow 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".
← → move through sections and cards