My understanding is that you cannot reference a variable before it has been declared, and that all code (including instance initializers) that is within the body of a class,
The order of declaration is not important. You could also write:
public class WhyIsThisOk {
{
a = 5;
}
public WhyIsThisOk() {
}
public static void main(String[] args) {
System.out.println(new WhyIsThisOk().a);
}
int a = 10;
}
Important is, that the compiler copies (top down) first a=5
and then a=10
into constructor so it looks like:
public WhyIsThisOk() {
a = 5;
a = 10;
}
Finally look at this example:
public class WhyIsThisOk {
{
a = get5();
}
public WhyIsThisOk() {
a = get7();
}
public static void main(String[] args) {
System.out.println(new WhyIsThisOk().a);
}
int a = get10();
public static int get5() {
System.out.println("get5 from: " + new Exception().getStackTrace()[1].getMethodName());
return 5;
}
public static int get7() {
System.out.println("get7 from: " + new Exception().getStackTrace()[1].getMethodName());
return 7;
}
public static int get10() {
System.out.println("get10 from: " + new Exception().getStackTrace()[1].getMethodName());
return 10;
}
}
Output is:
get5 from:
get10 from:
get7 from:
7