What is the explanation of this results in Java ?

Posted by M.H on Stack Overflow See other posts from Stack Overflow or by M.H
Published on 2010-06-08T21:33:18Z Indexed on 2010/06/08 21:42 UTC
Read the original article Hit count: 199

Filed under:

I have the following code :

public class Main {
    private int i = j; //1
    private int j = 10; 

    public static void main(String[] args) {
        System.out.println((new Main()).i);      
    }
}

and there is a compiler error in line 1 because an illegal forward reference.
But when I am trying the following code :

public class Main {
    int i = getJ();  //1

    int getJ(){
       return j;
    }
    int j=10;
    public static void main(String[] args) {
        System.out.println(new Main().i);
    }
}

it works fine and the result is 0.
Why there is no illegal forward reference in line 1 here?.The two codes look similar to me.

© Stack Overflow or respective owner

Related posts about java