The Plain Picture#
A family recipe book handed down to you. You get every recipe your parents had, for free. You can add your own new recipes, and you can rewrite a few of theirs your own way — but you didn't have to write the whole book from scratch.
The Real Names#
Inheritance lets a class — the subclass (child) — reuse and extend another — the superclass (parent) — using
extends.The subclass inherits the superclass's fields and methods (private ones exist inside the object but aren't directly accessible from the subclass).
It models an "is-a" relationship: a
MultipleChoiceis aQuestion.super(...)calls the parent's constructor; it must be the first line of the subclass constructor.super.method()calls the parent's version of a method.Every class ultimately extends
Object, the root of all Java classes (where the defaultequals,hashCodeandtoStringcome from).A Java class can extend only one class (single inheritance). Why — and how interfaces fill the gap — is Ch 6.
Under the Hood#
abstract class Question { // "abstract" is explained in Ch 5 — ignore it for now
protected final String text; // protected: visible to subclasses
protected final int points;
Question(String text, int points) {
this.text = text;
this.points = points;
System.out.println("Question constructor: " + text);
}
...
}
class MultipleChoice extends Question {
private final char correctOption; // an extra field only MCQs have
MultipleChoice(String text, int points, char correctOption) {
super(text, points); // parent sets up text and points FIRST
this.correctOption = correctOption;
}
}When you run new MultipleChoice(...), the parent's constructor runs first (that's why the output prints
Question constructor: ... for every question) — the parent part of the object must be ready before the child part builds on it.
┌──────────────────────┐
│ Object │ equals, hashCode, toString
└──────────▲───────────┘
│ extends
┌──────────┴───────────┐
│ Question │ text, points, grade(), describe()
└──▲────────▲───────▲──┘
│ │ │
┌────────────┴─┐ ┌────┴─────┐ ┌┴────────────┐
│MultipleChoice│ │TrueFalse │ │ShortAnswer │
│correctOption │ │correct │ │expected │
└──────────────┘ └──────────┘ └─────────────┘Check yourself
4 questionsWhat relationship does inheritance model?
Show answerHide answer
"Is-a" — a subclass is a special kind of its superclass.
In what order do constructors run when you create a subclass object?
Show answerHide answer
The superclass constructor first (all the way up to Object), then the subclass constructor.
What does super(text, points) do, and where must it go?
Show answerHide answer
Calls the parent's constructor with those arguments; it must be the first statement in the subclass constructor.
How many classes can a Java class extend?
Show answerHide answer
One.