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.
Methods can be used before they are declared.
private int j = 10;is an executable statement that must be executed at some point in time. Therefore, the ordering of field declarations is meaningful.A method declaration is not itself executable.
Therefore, the ordering of method is completely meaningless.