How does this code work fine and prints 9?
public class Dog{
static {
age=9;
}
static int age=7;
}
And this code doesn't compile(illegal forward reference)? Notice I changed age in static block.
public class Dog{
static {
age++;
}
static int age=7;
}
Another question is how do both of them even work? From my prior Java knowledge I knew a rule that:
you can't access variable before declaring them
. So how does static block know what variable age actually is?
Static blocks and static variable initialisations are executed in the order in which they appear in source file. (java documentation point 9
In Above case, you are doing an assignment before declaring a variable which is permitted by java in certain cases. Forward References During Field Initialization
In this case, you are reading it before declaring it which is not permitted. That's why you are getting an illegal forward reference exception.