Java static final field initialization order

后端 未结 4 753
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 16:51

I tried to understand the behavior of initialization order when static fields are initialized with a reference to the same enclosing class object.

public          


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 17:23

    Static variables are initialized when the class gets loaded by class loader. So when first line “static Test t=new Test();” gets executed, the value of int “a” is not yet initialized, hence it is showing as 0. But other 3 cases (i.e. removing static, adding final or without any modifier) what happens a gets initialized at the time of Object creation of Test class, which is happening in the first line so it is showing the value “5”.

提交回复
热议问题