【发布时间】:2018-06-12 10:26:58
【问题描述】:
我正在使用 Java 中的前向引用,想知道为什么 Java 允许使用 ClassName(在静态变量中)或 this 引用在实例变量的情况下进行前向引用? 在 JVM 级别发生的后台进程是什么?例如:
静态前向参考-
class StaticForwardReferences {
static {
sf1 = 10; // (1)
int b = sf1 = 20; // (2)
int c = StaticForwardReferences.sf1; // (3) Works fine
// Above statement allows the allocation of value of 'sf1'
// to variable 'c' just because it is accessed with class name
// instead of direct name
// whereas below statement throws illegal forward reference
// error at compile time
System.out.println(sf1); // (4) Illegal forward reference
}
static int sf1 = sf2 = 30;
static int sf2;
public static void main(String[] args) {}
}
如果我们打印变量 @987654324 的值,是否有任何类型的临时存储,当我们通过在声明之前分配变量(如上面(1)和(2)步骤中所做的那样)进行前向引用时存储值@,它显示最近分配给sf1的值。
非静态前向引用-
class NonStaticForwardReferences {
{
nsf1 = 10;
System.out.println(this.nsf1); // 10
nsf1 = sf1;
// System.out.println(nsf1); Illegal forward reference
int b = nsf1 = 20;
int c = this.nsf1;
System.out.println(c); // 20
// why variable 'c' is initialized to 20 when used with 'this' reference
// instead of showing illegal forward reference, how it works in the background?
}
int nsf1 = nsf2 = 30;
int nsf2;
static int sf1 = 5;
public static void main(String[] args) {}
}
请说明上述两种情况在幕后发生的后台进程。提前致谢! :)
【问题讨论】:
标签: java static non-static forward-reference