Chaining with this() and super()¶
โ Java 17 ยท Building Objects the Right Way with Constructors ยท 2/3
Overloaded constructors often repeat the same code. Two calls let a constructor delegate the work.
Reusing a constructor with this()¶
public Movie(String t) {
Movie(t, 90); // โ a constructor can't be called by name
new Movie(t, 90); // โ ๏ธ compiles, but builds a second, wasted object
}
public Movie(String t) {
this(t, 90); // โ
runs Movie(String, int) on THIS object
}
Don't confuse this (the current object) with this() (a call to another constructor of the same class).
The rules of this()¶
1: public class Episode {
2: Episode(int n, String t) { }
3: Episode(int n) {
4: System.out.println("new episode");
5: this(n, "Untitled"); // โ not the first statement
6: }
7: Episode() { this("Pilot"); }
8: Episode(String t) { this(); } // โ 7 and 8 call each other forever
9: }
- First statement: nothing may run before it (a comment is fine).
- Only once: being first, it can't appear twice.
- No cycles: constructors can't end up calling each other in a loop.
Building the parent first with super()¶
Every constructor starts by calling either this(โฆ) or a parent constructor with super(โฆ):
public class Content {
String title;
public Content(String t) { title = t; }
}
public class Movie extends Content {
public Movie(String t) { super(t); } // the Content part is built first
}
new Movie("Dune") โ Movie(String) โ Content(String) โ Object(). The parent part of the object is always built before the child's.
super() follows the same rules as this(): first statement, once, and a constructor can't call both.
The hidden super()¶
A constructor that doesn't start with this(โฆ) or super(โฆ) gets super(); added by the compiler. These three classes are identical:
public class Clip { }
public class Clip { public Clip() { } }
public class Clip { public Clip() { super(); } }
When the parent needs arguments¶
The hidden super() can fail:
class Content {
Content(String t) { }
}
class Movie extends Content { } // โ default constructor calls super(): no match
class Series extends Content { Series() { } } // โ same hidden super()
class Trailer extends Content {
Trailer() { super("Untitled"); } // โ
passes what the parent needs
}
If the parent has no no-argument constructor, every child constructor must call super(โฆ) with arguments, or this(โฆ). And super(โฆ) always targets the direct parent only.
The lab chains this() and super() and prints each step, so you can watch the order.