Why can my instance initializer block reference a field before it is declared?

倖福魔咒の 提交于 2019-12-01 16:02:20

问题


My understanding is that you cannot reference a variable before it has been declared, and that all code (including instance initializers) that is within the body of a class, but outside of any method, is executed in order before constructor when the object is created (the exception being static variables and initializer blocks, which are run in order at the beginning of the program, to initialize the entire class). Why, then, does the following code compile (and run!):

public class WhyIsThisOk {
    { a = 5; } // why is this ok???
    int a = 10;

    public WhyIsThisOk() {
    }

    public static void main(String[] args) {
        WhyIsThisOk why = new WhyIsThisOk();
        System.out.println(why.a); // 10
    }
}

回答1:


From docs:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

The above statement is slightly misleading, because if we follow the explanation of the above doc we can rewrite the original code like this:

public class WrongVersionOfWhyIsThisOk {

    int a = 10;

    public WhyIsThisOk (){
        a = 5;
    }

    public static void main(String[] args){
        WrongVersionOfWhyIsThisOk why = new WrongVersionOfWhyIsThisOk ();
        System.out.println(why.a);
    }
}

But running WrongVersionOfWhyIsThisOk will produce 5 instead of 10 that original code produces.

But in reality it is both the initializer block and variable assignment are copied into constructor:

public class RightVersionOfWhyIsThisOk {

    int a;

    public RightVersionOfWhyIsThisOk (){
        a = 5;
        a = 10;
    }

    public static void main(String[] args){
        RightVersionOfWhyIsThisOk why = new RightVersionOfWhyIsThisOk ();
        System.out.println(why.a);
    }
}

Update:

Here is the doc describing in detail the initialization order and constructor invocation:

4) 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.

5) Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.




回答2:


The instance initialization blocs are called at the instance creation time.so it is normal that After the creation of the why object, it Works.

The order of initialisation is: 1) static bloc 2)constructor 3)instance blocs on order of appearance




回答3:


The contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents).

So you can provide reference to any variables as they will not be used unless a constructor is invoked aka. object is created.




回答4:


From docs:

8.3.2.3. Restrictions on the use of Fields during Initialization

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer
    of C.

  • The usage is not on the left hand side of an assignment.

  • The usage is via a simple name.

  • C is the innermost class or interface enclosing the usage.

It is a compile-time error if any of the four requirements above are not met

In this case, the usage is on the left hand side of the assignment, so it is not a compile-time error.




回答5:


The order of declaration is not important. You could also write:

public  class WhyIsThisOk {

    {
        a = 5;
    }

    public WhyIsThisOk() {
    }

    public static void main(String[] args) {
        System.out.println(new WhyIsThisOk().a);
    }

    int a = 10;
}

Important is, that the compiler copies (top down) first a=5 and then a=10 into constructor so it looks like:

public WhyIsThisOk() {
    a = 5;
    a = 10;
}

Finally look at this example:

public class WhyIsThisOk {

    {
        a = get5();
    }

    public WhyIsThisOk() {
        a = get7();
    }

    public static void main(String[] args) {
        System.out.println(new WhyIsThisOk().a);
    }

    int a = get10();

    public static int get5() {
        System.out.println("get5 from: " + new Exception().getStackTrace()[1].getMethodName());
        return 5;
    }

    public static int get7() {
        System.out.println("get7 from: " + new Exception().getStackTrace()[1].getMethodName());
        return 7;
    }

    public static int get10() {
        System.out.println("get10 from: " + new Exception().getStackTrace()[1].getMethodName());
        return 10;
    }
}

Output is:

get5 from: <init>
get10 from: <init>
get7 from: <init>
7


来源:https://stackoverflow.com/questions/48215842/why-can-my-instance-initializer-block-reference-a-field-before-it-is-declared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!