当我运行这个程序时,有时会打印出55,尽管我确信6是正确的行为。
难道是我看错了?
public class Test {
static int a = 55;
static {
a = 6;
}
public static void main(String abc[]){
// a is 6
System.out.println(a);
}
}
编辑
我认为 Cularis 做对了,当我改变静态 block 以及实例化和初始化的顺序时,打印了 55。它确实是按纹理顺序排列的。
public class Test {
static {
a = 6;
}
static int a = 55;
public static void main(String abc[]) {
// a is 55
System.out.println(a);
}
}
最佳答案
看看 Java Language Specification ,特别是
12.4.2 Detailed Initialization Procedure
... 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, except that final class variables and fields of interfaces whose values are compile-time constants are initialized first (§8.3.2.1, §9.3.1, §13.4.9). ...
关于java - 初始化类变量时类变量的类加载顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6717817/