super and this: Constructor Chaining

OOP · lesson 18 of 43 · 3 min read

How this(...) delegates sideways and super(...) goes up, and why the order is fixed.

Open this lesson in the learning hub

Key points

  • this(...) calls another constructor of the same class. super(...) calls the parent one.
  • Either must be the first statement, and you cannot use both. Write no call and Java inserts super() for you.
  • So every chain ends at Object first, and the bodies then finish in reverse: parent, then child.
  • Keep one constructor that does the real work and have the rest delegate to it with this(...).
  • Never call an overridable method from a constructor: the subclass field it reads has not been assigned yet.
  • super.method() is different: it runs the parent version of an overridden method, at any time.

Example

public class Main {
    static class Person {
        final String name;
        Person(String name) {
            this.name = name;
            System.out.println("  2. Person(String)");
        }
    }

    static class Employee extends Person {
        final String team;
        final int level;

        Employee(String name) {
            this(name, "unassigned", 1);     // this(...) delegates sideways, first statement
            System.out.println("  4. Employee(String)");
        }

        Employee(String name, String team, int level) {
            super(name);                     // super(...) goes up first, first statement
            this.team = team;
            this.level = level;
            System.out.println("  3. Employee(String,String,int)");
        }

        @Override public String toString() { return name + " / " + team + " / L" + level; }
    }

    public static void main(String[] args) {
        System.out.println("1. new Employee(Ada)");
        System.out.println(new Employee("Ada"));

        System.out.println("1. new Employee(Grace, Core, 5)");
        System.out.println(new Employee("Grace", "Core", 5));
    }
}

Constructors chain to the top before any body runs, then finish parent first.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.