Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - passing instance variables to this() method

Tags:

java

I was learning about using this() to call an overloaded constructor and came across this restriction:

You can not use any instance variable of the constructor's class in a call to this()

For example:

class Test{
    int x;

    public Test() {
        this(x); //Does not compile
    }

    public Test(int y) {}

    void method1() {
        method2(x); //OK
    }

    void method2(int y) {}
}

I know that no need to pass an instance field to a constructor since it's visible by default. However, why is the same restriction not applied to instance methods?

like image 453
mrboieng Avatar asked Aug 15 '26 02:08

mrboieng


1 Answers

There is one other requirement in Java: constructor calls (using this() must be performed first within any constructor. The constructors will initialize the object.

After that the instance fields are initialized after these initial calls. So as the field values are now well defined, you can use them for anything including calling other methods.

However, before the initial constructor calls, the fields are in an undefined state and cannot be used as argument for other constructor calls.


For these kind of things you need to look in the JLS:

  1. If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.

  2. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.

So the instance variables are only initialized after the constructor calls. This makes sense, because it would be strange to first assign it the default value (zero or null) and then assign it another value from within a constructor.

like image 159
Maarten Bodewes Avatar answered Aug 16 '26 16:08

Maarten Bodewes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!