java – Why can the constructor this () super () be written only at the beginning?

Question: Question:

Why did this() super() prohibit writing other than at the beginning?
Isn't it annoying when you have to do something before calling this() or super() ?
why is it.

public class Instance{
  String name;
  public Instance(){
    //ここに処理があるとエラーが出る
    this("Sample");
  }
  public Instance(String name){
    //処理…
  }
}

You can also do something like Instance instance=getInstance(); .

public class Instance{
  String name;
  public static Instance getInstance(){
    //処理
    return new Instance("Sample");
  }
  private Instance(String name){
    //処理…
  }
}

That's fine, but I was a little worried, so please let me know.

Answer: Answer:

This constraint is correctly only in the constructor.

call to super () must be first statement in constructor.

As per the error message in, this is to prevent access to objects in an indefinite state that have not yet been created.

It is easy to understand when considering the following situations.

class Instance {
    protected String name;
    public Instance() {
        this("BaseType");
    }
    public Instance(String name) {
        this.name = name;
    }
}

class SubInstance extends Instance {
    public SubInstance() {
        this.name = "SubType";
        super(); // Illegal Code
    }
}

At the time of calling super() of SubInstance , the constructor of Instance has not been executed yet.

This malicious code rewrites the name field to SubType at the beginning of SubInstance , but if it can then be initialized by calling super() , the name field will be overwritten with BaseType .

You might think it's not a big deal if it's just an unexpected field value. But what if you can access a null reference because it hasn't been initialized yet?

You can see that the same can be said for this() .

Scroll to Top