Lab: a streaming catalog built on inheritance¶
☕ Java 17 · Building Classes on Top of Other Classes · 3/3
Goal: build a four-level hierarchy, from Object down to Documentary, and see one object use members from every level.
Setup: in an empty folder, create one file per class: Content.java, Series.java, Movie.java, Documentary.java, and StreamingCatalog.java for main. No package.
Step 1 — The parent¶
title and play() live here, and only here.
Step 2 — A first child¶
Series inherits title and play() and adds only seasons.
Step 3 — Use it¶
public class StreamingCatalog {
public static void main(String[] args) {
Series dark = new Series();
dark.title = "Dark"; // from Content
dark.seasons = 3; // from Series
dark.play(); // from Content
System.out.println(dark.title + " has " + dark.seasons + " seasons");
System.out.println(dark.toString()); // from Object
}
}
The last line is Object's default toString(): the class name, @, and a hash code that will differ on your machine.
Step 4 — Grow the tree¶
public class Movie extends Content {
int durationMinutes;
}
public class Documentary extends Movie {
String topic;
}
Add to main:
Movie inception = new Movie();
inception.title = "Inception";
inception.durationMinutes = 148;
inception.play();
Documentary ourPlanet = new Documentary();
ourPlanet.title = "Our Planet"; // Content
ourPlanet.durationMinutes = 50; // Movie
ourPlanet.topic = "Nature"; // Documentary
ourPlanet.play(); // Content
System.out.println(ourPlanet.title + " is about " + ourPlanet.topic
+ " and lasts " + ourPlanet.durationMinutes + " minutes");
One Documentary object holds data from Content, Movie and Documentary.
Step 5 — One place to fix¶
In Content.java, change the message:
Recompile and run: Dark, Inception and Our Planet all say Now streaming. One line changed, in one file, and every kind of content picks it up.
← Family rules · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)