What is called a forward reference in Java?

前端 未结 4 1131
借酒劲吻你
借酒劲吻你 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:12

    public class AnyCode {
    
        void print() {
            System.out.println("Value of j - " + j);   // legal
            System.out.println("Value of i  - " + i);  // legal
        }
    
        // CASE - 1 
        int k = i;         // illegal
        int i; 
    
        // CASE - 2 
        int l = j;         // legal
        static int m = j;  // illegal
        static int j;
    
        // CASE - 3 
        A aObj = bObj;     // illegal
        B bObj = new B();
    
        public static void main(String[] args) {
    
            /* 
               Note :- here anyCode act as a local variable and get space on stack 
               whereas the object it is referring to is present on heap. And you 
               cannot forward reference a local variable. 
            */
    
            anyCode.print();    // 'Cannot find symbol' error
            AnyCode anyCode = new AnyCode();
        }
    
    }
    
    class A {
    
    }
    
    class B {
    
    }
    

    *********Refer CASE - 1*********

    Forward referencing instance variable is not allowed as compiler is not sure of the type of value we are forward referencing or it might even be possible that no such variable exist.

    Consider an example :-

    int a = b;
    boolean b = false;
    

    If forward referencing is allowed in above case then it might create a havoc.

    int a = b; // What is b? is it a primitive variable or a value or a object reference
    

    in the above example i have decided not to declare b and now if such assignment were allowed by java, then it will be a nightmare.

    **********Refer CASE - 2*********

    Static variables are loaded before instance variables and hence forward referencing static variables and assigning them to instance variable is perfectly fine

提交回复
热议问题