我已经读过this question on legality of forward references 了,但不清楚Java语言中forward references
的含义。有人可以借助示例进行解释吗?
最佳答案
这是一个专门的编译错误。及其所有关于类变量声明的顺序。让我们使用一些代码进行说明:
public class ForwardReference {
public ForwardReference() {
super();
}
public ForwardReference echoReference() {
return this;
}
public void testLegalForwardReference() {
// Illustration: Legal
this.x = 5;
}
private int x = 0;
// Illustration: Illegal
private ForwardReference b = a.reference();
private ForwardReference a = new ForwardReference();
}
如您所见,Java允许您在类方法中引用类变量,即使变量的声明在方法之后出现在之后。这是(合法)前向引用的示例,并且Java编译器内置了对此的支持。
您不能执行的操作是,声明一个依赖于另一个尚未声明的类变量'b'的类变量'a'。从属类变量声明必须以与它们的依赖相反的顺序出现。
在切线上,如果您的代码包含非法引用错误,则大多数(如果不是全部)IDE会警告您。
JLS的section 8.3.2.3涵盖了非法的前向引用。
关于java - 在Java中什么叫做前向引用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14509481/