Reputation: 63
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?
Upvotes: 0
Views: 67
Reputation: 2900
public class Dog{
static {
age=9;
}
static int age=7;
}
Static blocks and static variable initialisations are executed in the order in which they appear in source file. (java documentation point 9
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
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
The use is on the left-hand side of an assignment;
public class Dog {
static {
age++;
}
static int age=7;
}
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.
j = 200; // ok - assignment
j = j + 1; // error - right hand side reads before declaration
Upvotes: 2