在Java中什么叫做前向引用? [英] What is called a forward reference in Java?

查看:42
本文介绍了在Java中什么叫做前向引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过有关正向引用合法性的问题,但不清楚是什么是指Java语言中的前向引用.有人可以在示例的帮助下进行解释吗?

I have been through this question on legality of forward references but not clear as to what is meant by forward references in Java language . Can someone please explain with the help of an example ?

推荐答案

这是编译错误.及其所有关于类变量声明的顺序.让我们使用一些代码进行说明:

This is specifically a compilation error. And its all about ordering of class variable declarations. Let's use some code for illustrative purposes:

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允许您在 class方法中引用 class变量,即使变量的声明在之后方法.这是一个(合法的)前向引用的示例,并且Java编译器内置了对此引用的支持.

As you can see, Java allows you to reference a class variable in a class method, even if the declaration of the variable comes after the method. This is an example of a (legal) forward reference, and support for this is built into the Java compiler.

无法执行的操作是,声明一个类变量"a",该变量取决于尚未声明的另一个类变量"b".从属类变量声明必须以与它们的依赖关系相反的顺序出现.

What you cannot do though, is declare a class variable 'a' that depends on another class variable 'b' that has not been declared yet. Dependent class variable declarations must appear in reverse order of their dependency.

在切线上,如果您的代码包含非法引用错误,则大多数(如果不是全部)IDE会警告您.

On a tangent, Most, if not all IDE's will warn you if your code contains illegal reference errors.

第8.3.2.3节<的JLS.

这篇关于在Java中什么叫做前向引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆