有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么静态初始化块中不允许使用限定的静态final变量?

案例1

class Program {
    static final int var;

    static {
        Program.var = 8;  // Compilation error
    }

    public static void main(String[] args) {
        int i;
        i = Program.var;
        System.out.println(Program.var);
    }
}

案例2

class Program {
    static final int var;

    static {
        var = 8;  //OK
    }

    public static void main(String[] args) {
        System.out.println(Program.var);
    }
}

为什么案例1会导致编译错误


共 (2) 个答案

  1. # 1 楼答案

    JLS持有答案(请注意粗体声明):

    Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator. [§16]

    这意味着在分配静态最终变量时必须使用“简单名称”——即不带任何限定符的变量名称

  2. # 2 楼答案

    显然,这是一种廉价的语法技巧,用于限制类本身中的确定(非)赋值分析

    如果字段在语法上用类名限定,则代码在另一个类中通常为,而分析无法到达该类

    在你的例子中,这个技巧失败了。其他奇怪的例子:

    static class A
    {
        static final int a;
        static
        {
            // System.out.println(a); // illegal
            System.out.println(A.a);  // compiles!
            a = 1;
        }
    }
    

    如果他们有更多的资源,他们可能会制定更好的规则。但我们现在不能改变规格