explain java compile order

前端 未结 1 2016
有刺的猬
有刺的猬 2020-12-12 02:23

v2 is null when it enters A\'s c\'tor at the first time, but if I put v2\'s declaration & initialization before instance it will h

相关标签:
1条回答
  • 2020-12-12 03:12

    The static variables are initialized in the order they appear in the source file when class A is initialized (before main is executed).

    • first v1
    • then instance (which prints A c'tor v1 [ab] v2 [null] since its initialization involves creating an instance of A) - it is initialized before v2, which is why v2 is still null.
    • then v2

    After they are initialized, the main method is executed, and produces the next 3 output lines. The creation of the new instance of A inside the main method produces a different output than the previous constructor call, since at this point both v1 and v2 are initialized.

    EDIT :

    Regarding your updated question :

    If you follow the initialization procedure in JLS 12.4.2:

    1. Otherwise, record the fact that initialization of the Class object for C is in progress by the current thread, and release LC. Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions.

    ...

    1. Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

    As you can see, the final static variables whose values are compile-time constant expressions are initialized before the rest of the static variables. Therefore changing the value of v2 to the constant "ab" causes v2 to be initialized before the instance variable, which explains the different output.

    0 讨论(0)
提交回复
热议问题