gpt4 book ai didi

java - 为什么静态初始化 block 中不允许使用限定的静态最终变量?

转载 作者:行者123 更新时间:2023-12-03 23:14:28 24 4
gpt4 key购买 nike

案例一

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);
}
}

为什么Case 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]

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

关于java - 为什么静态初始化 block 中不允许使用限定的静态最终变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com