Java - Why constructor call must be the first statement in a constructor

When you define a Java class constructor that calls another constructor, you need to place the constructor call at the top of the constructor definition.

For example, the following Product class has two constructors, with the first constructor calling the second:

class Product {
    public String name;

    public Product() {
        this("Mouse");
        this.name = "Keyboard";
    }

    public Product(String name) {
        this.name = name;
    }
}

When you move the constructor call below the this.name assignment, Java will throw the call to this must be first statement in constructor:

class Product {
    public String name;

    public Product() {
        this.name = "Keyboard";
        this("Mouse"); // ERROR
    }

    public Product(String name) {
        this.name = name;
    }
}

This is because when you run other statements before the call to the constructor, then you might call some methods or states that are not yet defined.

The same happens when you extend a superclass. You need to call the super() constructor before anything else.

When other statements before the super() constructor are allowed, then you might try to call or manipulate class members and methods that are not yet constructed.

It’s a rule set up by Java itself to prevent errors by disabling dynamic orders between the initialization of the class object and other assignments and operations.

So when you need to perform a constructor chaining or call the superclass constructor, make sure that you do it on the first line.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.