为什么静态字段没有及时初始化? [英] Why static fields are not initialized in time?
本文介绍了为什么静态字段没有及时初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码打印 null
一次。
class MyClass {
private static MyClass myClass = new MyClass();
private static final Object obj = new Object();
public MyClass() {
System.out.println(obj);
}
public static void main(String[] args) {}
}
为什么在构造函数运行之前没有初始化静态对象?
Why are the static objects not initialized before the constructor runs?
更新
我刚刚复制了这个示例程序而没有注意,我以为我们正在谈论2个Object字段,现在我看到第一个是MyClass字段..:/
I'd just copied this example program without attention, I thought we were talking about 2 Object fields, now I saw that the first is a MyClass field.. :/
推荐答案
因为静态按照源代码中给出的顺序进行初始化。
Because statics are initialized in the order they are given in source code.
检查出来:
class MyClass {
private static MyClass myClass = new MyClass();
private static MyClass myClass2 = new MyClass();
public MyClass() {
System.out.println(myClass);
System.out.println(myClass2);
}
}
这将打印:
null
null
myClassObject
null
编辑
好的,让我们把它画得更清楚。
Ok let's draw this out to be a bit more clear.
- 静态按源代码中声明的顺序逐个初始化。
- 自第一次静态在其余部分初始化之前,在其初始化期间,其余的静态字段为空或默认值。
- 在第二次静态启动期间,第一个静态是正确的,但其余的仍为空或默认。
这是否清楚?
编辑2
正如Varman指出的那样,在初始化时对自身的引用将为null。如果你考虑一下这是有道理的。
As Varman pointed out the reference to itself will be null while it is being initialized. Which makes sense if you think about it.
这篇关于为什么静态字段没有及时初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文