JAVA initialization blocks

后端 未结 6 1751
谎友^
谎友^ 2021-01-21 18:03

As some sources say, the Java instance initialization blocks are executed whenever instance is created or right before constructor. But imagine this case:

public         


        
6条回答
  •  借酒劲吻你
    2021-01-21 18:25

    There's a specific initialization procedure explained in the JLS, but let me distill the most critical parts:

    • What happens in terms of initializing a class is implementation-dependent of the JVM.
    • The super class is initialized before its subclasses (step 7) if the super class has not yet been initialized.
    • Evaluate all static initializers and fields as if they were a single block in textual order. That last part is important; it means that what's seen first is initialized first.

    This is why you see the behavior you do - because Main is a subclass to Foo, it isn't yet initialized, so its static block isn't been evaluated at that moment.

    Consequently, Main's constructor isn't executed until after Foo's constructor, since there is an implicit call to super() in the subclass.

提交回复
热议问题