分析以下静态 block 中的一些奇怪场景:
static {
System.out.println("Inside Static Block");
i=100; // Compilation Successful , why ?
System.out.println(i); // Compilation error "Cannot reference a field before it is defined"
}
private static int i=100;
虽然相同的代码在使用时运行良好:
static {
System.out.println("Inside Static Block");
i=100; // Compilation Successful , why ?
System.out.println(MyClass.i); // Compiles OK
}
private static int i=100;
不确定为什么变量初始化不需要使用类名访问变量而 SOP 需要?
最佳答案
这是因为 restrictions on the use of Fields during Initialization .特别是,在声明它们的行之前在静态初始化 block 内使用静态字段只能在表达式的左侧(即赋值),除非它们是完全限定的(在您的情况下为 MyClass.i
)。
例如:如果你在 i = 100;
之后插入 int j = i;
你会得到同样的错误。
解决问题的明显方法是在静态初始化 block 之前声明 static int i;
before。
关于 java : accessing static variables inside static block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635200/