extends, and what a child inherits¶
โ Java 17 ยท Building Classes on Top of Other Classes ยท 1/3
Why inheritance?¶
Movies and series both have a title, a duration and can be played. Copying those members into both classes means fixing every bug twice, until the copies drift apart.
Inheritance solves it: a new class automatically receives the members of an existing one.
| Term | Meaning | Example |
|---|---|---|
| Parent (superclass) | the class inherited from | Content |
| Child (subclass) | the class that inherits | Movie |
extends¶
public class Content {
String title;
int durationMin;
void play() {
System.out.println(title);
}
}
public class Movie extends Content {
String director;
}
extends Content right after the class name makes Movie a child of Content. Movie now has title, durationMin and play() without rewriting them, plus its own director. The parent needs no special code: it just must not be final.
Several levels¶
Inheritance is transitive:
public class Content { }
public class Movie extends Content { } // child of Content
public class Documentary extends Movie { } // child of Movie
Documentary's direct parent is Movie only. Content is an indirect ancestor, but its members still reach Documentary through Movie.
What a child can really use¶
Access modifiers decide which inherited members the child can touch:
public class Content {
private int views;
protected String title;
public int getViews() { return views; }
}
public class Movie extends Content {
void describe() {
title = "Inception"; // โ
protected
getViews(); // โ
public
views = 10; // โ private: not accessible
}
}
| Modifier | Usable in a child class? |
|---|---|
public |
always |
protected |
always, in any package |
| none (package access) | only if child and parent are in the same package |
private |
never directly: go through a method like getViews() |
A Movie object still contains the views data. The child simply can't name it: it uses the parent's public methods instead.
Inheritance also comes with a few strict family rules.