NullPointerException with static variables

后端 未结 2 1623
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 14:26

I just hit very strange (to me) behaviour of java. I have following classes:

public abstract class Unit {
    public static final Unit KM = KMUnit.INSTANCE;
             


        
2条回答
  •  灰色年华
    2021-02-15 14:58

    I would expect that:

    - KMUnit class is loaded and instance is created.
    - MeterUnit class is loaded and instance is created.
    - Unit class is loaded and both KM and METERS variable are initialized, they are final so they cant be changed.
    

    Even without going into the the language spec it is easy to see why the above sequence is impossible.

    KMUnit extends Unit. To create the static field KMUnit.INSTANCE its class KMUnit has to be created. And to create KMUnit its super class Unit has to be created. Finally to create the class Unit its static fields KM and METERS has to be assigned.

    But we got here by trying to create the class KMUnit and we haven't loaded the class Meters yet. So it impossible that the static fields of the super class are assigned correct values (i.e. references to fully constructed object).

    There are two problems in the steps you describe:

    The error in the steps you describe is that you are delaying loading of Unit, which cannot be done.

    Hope this helps. Static initializers are not easy to understand and their specs even less so. It is perhaps easier to rationalize why something cannot be done, hence my non-formal answer.

提交回复
热议问题