Are fields initialized before constructor code is run in Java?

后端 未结 5 2212
梦谈多话
梦谈多话 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:35

    The initialization sequence is specified in JLS 12.5:

    1.First, memory is allocated for the new object

    2.Then all instance variables in the object (including the ones defined in this class and all of its superclasses) are initialized to their default values

    3.Finally, the constructor is called.

    https://stackoverflow.com/questions/26552799/which-run-first-default-values-for-instance-variables-or-super-constructors

提交回复
热议问题