Search code examples
javaforward-reference

What is a forward reference in Java?


I have been through this question on the legality of forward references, but I don't know what "forward references" means in Java. Can someone please explain with the help of an example?


Solution

  • 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.