我只花了五分钟在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());
}
}
Run Code Online (Sandbox Code Playgroud)
在java中我可以确定a1 总是在a2之前初始化吗?
谢谢.如果被问到或者它是否非常简单,Dw就可以了.
在java中我可以确定a1总是在a2之前初始化吗?
是的,因为规范(第12.4.2节)保证它(强调我的):
接下来,按文本顺序执行类的类变量初始值设定项和类的静态初始值设定项,或接口的字段初始值设定项,就好像它们是单个块一样.
请注意,常量比非常量更早初始化(步骤6与上面引用的步骤9相比).