JAVA / CHAPTER 11
Inheritance
AdvancedExtend behavior while preserving a usable superclass contract.
By the end of this chapter
- Trace superclass construction
- Override instance methods
- Choose inheritance only for a valid relationship
The idea
Inheritance creates a subclass that can reuse and specialize a superclass. An extends clause expresses the relationship, and super can call a superclass constructor or implementation. Construction initializes the superclass portion before the subclass constructor body completes. Overriding supplies a new implementation with a compatible method signature. The @Override annotation lets the compiler detect mistakes in your intended override.
A subtype should remain usable where its parent is expected. Inheriting solely to borrow code can produce a misleading model; composition is often clearer when one object contains or uses another. Private superclass fields are not directly accessible in subclass code, so a carefully designed parent exposes the protected or public behavior that extensions actually need.
class Notice {
String text() { return "Ready"; }
}
class UrgentNotice extends Notice {
@Override String text() { return super.text() + "!"; }
}
public class Main {
public static void main(String[] args) {
Notice n = new UrgentNotice();
System.out.println(n.text());
}
}Ready!
The overridden method is chosen for UrgentNotice. Its super call deliberately uses the parent implementation before adding the exclamation mark.
Try it yourself
Explain why a Playlist should contain songs rather than extend Song.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING