Inheritance
Brew Bar starts selling iced drinks. An iced latte is still a drink, with a name and a price, but it also needs an amount of ice. Copying the whole Drink class into a new file would mean fixing every future bug twice. Inheritance lets IcedDrink reuse everything Drink already has and add only what is new.
The rule
extendsmeans "is a": the child gets everything and adds more.
public class Drink {
protected String name;
protected int priceCents;
public Drink(String name, int priceCents) {
this.name = name;
this.priceCents = priceCents;
}
public String label() {
return name + " (" + priceCents + "c)";
}
}
public class IcedDrink extends Drink {
private int iceGrams;
public IcedDrink(String name, int priceCents, int iceGrams) {
super(name, priceCents); // build the Drink part first
this.iceGrams = iceGrams;
}
}Drink is the superclass (parent) and IcedDrink the subclass (child). The child automatically has name, priceCents and label(), and adds iceGrams. Private members of the parent still exist inside the child object but cannot be named from the child's code, which is why these fields are protected.
Rules that follow:
super(...)builds the parent part. It must be the first statement of the child's constructor. If you leave it out, Java insertssuper()with no arguments, which fails to compile here, becauseDrinkhas no such constructor.- Parents are built first. Constructors run from the top of the family tree down.
- One parent only. A class can extend exactly one class. (Several interfaces are allowed, as you will see.)
- Everything extends
Objectin the end, which is where methods liketoString()andequals()come from. - A child can stand in for its parent.
Drink d = new IcedDrink("Iced latte", 330, 80);is fine, because an iced drink is a drink. The reverse is not.
The shortcut
Before writing extends, say the sentence "Every ___ is a ___." If it is true, inheritance fits. If it sounds wrong, use a field instead ("an Order has drinks", so Order holds drinks rather than extending Drink).
Say the sentence
"Every order is a drink." That is false: an order contains drinks.
Drills
Answer fast — trust the rule.
With class Drink { Drink() { System.out.print("D"); } } and class IcedDrink extends Drink { IcedDrink() { System.out.print("I"); } }, what does new IcedDrink(); print?
Which line compiles?
What is wrong with class Mocha extends Drink, Dessert?
The IcedDrink constructor leaves out super(name, priceCents);. What happens?
Remember
extendsmeans "is a": the child gets everything and adds more.- Say "every ___ is a ___"; if it is false, use a field instead.
- Traps: forgetting
super(...), and trying to extend two classes.
