Are fields initialized before constructor code is run in Java?

后端 未结 5 2056
梦谈多话
梦谈多话 2020-11-22 06:39

Can anyone explain the output of following program? I thought constructors are initialized before instance variables. So I was expecting the output to be \"XZYY\".



        
5条回答
  •  醉酒成梦
    2020-11-22 07:31

    The correct order of initialisation is:

    1. Static variable initialisers and static initialisation blocks, in textual order, if the class hasn't been previously initialised.
    2. The super() call in the constructor, whether explicit or implicit.
    3. Instance variable initialisers and instance initialisation blocks, in textual order.
    4. Remaining body of constructor after super().

    See sections §2.17.5-6 of the Java Virtual Machine Specification.

提交回复
热议问题