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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.