小编Kai*_*ild的帖子

java:访问静态块内的静态变量

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

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;
Run Code Online (Sandbox Code Playgroud)

使用时,相同的代码工作正常:

static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(MyClass.i); // Compiles OK
}

private static int i=100;
Run Code Online (Sandbox Code Playgroud)

不确定为什么变量初始化在SOP需要时不需要使用类名进行变量访问?

java static

24
推荐指数
1
解决办法
2059
查看次数

标签 统计

java ×1

static ×1