What is called a forward reference in Java?

前端 未结 4 1147
借酒劲吻你
借酒劲吻你 2020-12-15 06:44

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 ple

4条回答
  •  忘掉有多难
    2020-12-15 07:02

    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();
    }
    

    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.

    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.

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

    Illegal forward references are covered in section 8.3.2.3 of the JLS.

提交回复
热议问题