有人可以向我解释为什么以下两个样本中的第一个编译,而第二个没有?注意唯一的区别是第一个明确地使用'.this'限定对x的引用,而第二个没有.在这两种情况下,显然都会尝试在初始化之前使用最终字段x.
我原以为两个样本都会被完全平等对待,导致两者都有编译错误.
1)
public class Foo {
private final int x;
private Foo() {
int y = 2 * this.x;
x = 5;
}
}
Run Code Online (Sandbox Code Playgroud)
2)
public class Foo {
private final int x;
private Foo() {
int y = 2 * x;
x = 5;
}
}
Run Code Online (Sandbox Code Playgroud) 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);
}
}
Run Code Online (Sandbox Code Playgroud)
class Program {
static final int var;
static {
var = 8; //OK
}
public static void main(String[] args) {
System.out.println(Program.var);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么案例1会导致编译错误?