我只花了五分钟在 SO 中找到重复项。
我的问题很简单。下面的代码总是有效吗?
public class LexicalOrderStatic {
private static Integer a1 = initA1();
private static Integer a2 = initA2();
private static Integer initA2(){
return new Integer(5) / a1;
}
private static Integer initA1(){
return new Integer(5);
}
public Integer getA1(){
return new Integer(a2);
}
public static void main(String[] args) {
LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
System.out.println(lexLuthor.getA1());
}
}
在 java 中,我可以确定 a1 总是在 a2 之前初始化吗?
谢谢。 dw 会问还是很简单就ok了。
最佳答案
In java can I be sure that a1 is always initialized before a2 ?
是的,因为规范(section 12.4.2)保证它(强调我的):
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
请注意,常量的初始化时间早于非常量(第 6 步与上面引用的第 9 步相比)。
关于java - Java中静态变量的文本顺序和初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22219512/