java - 初始化类变量时类变量的类加载顺序

标签 java class variables static

当我运行这个程序时,有时会打印出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/

相关文章:

java - 局部变量的默认值

java - 展平 map 中的列表列表

java - 导入oracle.jdbc无法解决

java - 如何捕获 java 中多个正则表达式匹配前后的文本?

python - Python 是否有类的默认构造函数?

python - 从字典值中命名以前 undefined variable 名称?

java - 跟踪在另一个 Android 应用中花费的时间

class - Linux 中抛出 IllegalAccessError ( suse 10)

java - 实例变量赋值不粘

linux - yad - 使用变量