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

标签 java static static-initialization static-initializer

我正在研究 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);
       }
    }

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

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

最佳答案

因为您的类变量在使用前出现,所以没问题。

这是 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.

关于java - 为什么静态初始化程序允许在 Java 中重新初始化静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44904324/

相关文章:

java - 如何在 Java 中将 Hex 字符串转换为 BufferedImage?

java - 如何避免在类初始化之前访问静态字段引起的问题?

c++ - 为什么以下代码可以正常编译,但在使用 static 时链接显示错误

c++ - C++中的静态全局标识符和非静态全局标识符有什么区别?

c++ - 动态库中共享库的静态初始值设定项

java - JSF 无法显示表中的数据

java - J2ME 中的 LWUIT : setting the style of a list cell when pressed

java - 单独文件中的 Android 服务不起作用

java - 使用静态初始化 block 来提高性能

java - 接口(interface)中的静态初始化