【发布时间】:2015-01-09 11:20:51
【问题描述】:
当静态字段使用对同一个封闭类对象的引用进行初始化时,我试图了解初始化顺序的行为。
public class Test {
static final Test t=new Test();
static int a=5;
Test(){
System.out.println("a="+a);
}
public static void main(String[] args) {
new Test();
}
}
上面这段代码的输出是:
a=0
a=5
如果我将变量 a 修改为普通 static 以外的任何其他值:
static final a=5;
a=5;
final a=5;
输出是:
a=5
a=5
为什么会这样?
请注意,即使两个t & a 都声明为static final,在这种情况下,t 在a 的声明之前,输出也是a=5 & a=5
【问题讨论】:
标签: java constructor static final static-members