Card 01/ 10

ConceptDifficulty: Intermediate1 min

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:

java
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.

What crosses the extends boundary and what does not
Declared in the parentIn the subclass?
public and protected fields and methodsYes, and reachable by name
Package-private members, same packageYes, and reachable by name
private fields and methodsPart of the object, not reachable by name
ConstructorsNo: each class writes its own
static methodsReachable, 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".