Java static final field initialization order

后端 未结 4 751
被撕碎了的回忆
被撕碎了的回忆 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

    Java Language specification is best source to understand all about initialization order. According to that in your scenario, static final field gets initialized before any class level variable gets initialized. When you remove the final, initialization was deferred. It should also be noted if you change

    static Test t=new Test();
    static int a=5;
    

    to

      static int a=5;
      static Test t=new Test();
    

    it will also print

     a = 5
     a = 5
    

    because of initialization order.

提交回复
热议问题