Skip to content

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: }
  1. First statement: nothing may run before it (a comment is fine).
  2. Only once: being first, it can't appear twice.
  3. 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.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

โ† Writing constructors ยท Next: the lab โ†’