25

分析以下静态块中的一些奇怪场景:

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 需要?

4

2 回答 2

15

This is because of the restrictions on the use of Fields during Initialization. In particular, the use of static fields inside a static initialization block before the line on which they are declared can only be on the left hand side of an expression (i.e. an assignment), unless they are fully qualified (in your case MyClass.i).

So for example: if you insert int j = i; right after i = 100; you would get the same error.

The obvious way to solve the issue is to declare static int i; before the static initialization block.

于 2013-05-19T13:41:19.360 回答
0

这是因为编译器在进行静态代码分析,例如实时变量分析(向后分析)。它为每个程序点计算变量是否会在下一次写入之前被读取。

于 2013-05-19T13:57:01.587 回答