为什么静态初始化程序允许在 Java 中重新初始化静态变量?

Why static initializer allow re-initialization of static variable in Java?

我正在研究 Java 中的静态初始值设定项。我通过下面给出的源代码来了:

    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }

我的问题是,为什么编译器不抱怨变量 count 在静态初始化程序块中被重新赋值为 count = 1 中的值 1。我知道 Java 允许前向引用,只要遵循 declaration-before-read 规则 (即任何标识符不应该在声明之前被读取),这是针对所有初始化程序的,如果not 那么引用(或标识符)必须出现在赋值的左侧。我也知道,如果多个静态初始化表达式和静态字段初始化块写在 class 中,那么它们的执行顺序是顺序的。

根据我的说法,执行流程应该是:加载 class,然后按顺序执行所有静态初始化程序(表达式和块),因此 count 将是初始化为值 5,然后将执行默认构造函数,调用 super() 并将实例变量 alive 初始化为默认值。但是为什么它没有抛出静态变量 count 已被重新初始化的错误(因为它不是前向引用的情况),而是给出了输出 1。 这是否意味着我们可以通过静态初始化块重新初始化静态变量?

因为你的 class 变量在使用前就出现了,没关系。

这是相同的

language specification#Static Initializers

A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.

Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.3 for the precise rules governing forward reference to class variables.

只要您在 class 中操作静态变量,它就会被初始化,您就不会从编译器中收到错误。如果您已将其声明为最终的,那么您提到的行为就会发生。请记住,static 意味着该变量在对象的所有实例之间共享,因此它只被初始化和内存分配一次。