Lab: building movies for the catalog¶
☕ Java 17 · Building Objects the Right Way with Constructors · 3/3
Goal: chain constructors with this() and super(), and watch the order in which their bodies run.
Setup: in an empty folder, create Content.java, Movie.java and StreamingPlatform.java.
Step 1 — The parent¶
public class Content {
String title;
Content(String t) {
title = t;
System.out.println("Content constructor: title set to " + title);
}
}
The print shows exactly when this constructor runs.
Step 2 — The full constructor¶
public class Movie extends Content {
private int minutes;
public Movie(String t, int min) {
super(t);
minutes = min;
System.out.println("Movie(String, int): runtime set to " + minutes + " minutes");
}
}
super(t) hands the title to Content first.
Step 3 — A shortcut constructor¶
public Movie(String t) {
this(t, 120);
System.out.println("Movie(String): default runtime applied");
}
public void play() {
System.out.println("Now playing: " + title + " (" + minutes + " min)");
}
this(t, 120) reuses the full constructor with a default runtime, so the logic lives in one place.
Step 4 — Build Dune¶
public class StreamingPlatform {
public static void main(String[] args) {
Movie dune = new Movie("Dune");
dune.play();
}
}
Predict the order, then run:
$ javac *.java
$ java StreamingPlatform
Content constructor: title set to Dune
Movie(String, int): runtime set to 120 minutes
Movie(String): default runtime applied
Now playing: Dune (120 min)
You called the one-argument constructor, yet Content prints first: Movie(String) → this(…) → Movie(String, int) → super(…) → Content(String). The bodies then finish from the top of the chain down.
Step 5 — Build Oppenheimer directly¶
Add to main:
---
Content constructor: title set to Oppenheimer
Movie(String, int): runtime set to 180 minutes
Now playing: Oppenheimer (180 min)
Only two messages: the default-runtime step never ran. But the parent still came first. Whatever constructor you start from, super runs before the child's own code.
← this() and super() · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)