问题
public class Test1 {
static{
a=20;
// System.out.println(a); //Line 4
}
static int a=getA();
private static int getA() {
return 10;
}
public static void main(String[] args) {
System.out.println(a);
}
}
Why it showing error ?but if remove the Line working fine ?
回答1:
It works if you declare a before the static initializer:
public class Test1 {
static int a=getA();
static{
a=20;
System.out.println(a);
}
private static int getA() {
return 10;
}
public static void main(String[] args) {
System.out.println(a);
}
}
Static initialization is done in the order it's written in the code. That means that in your code, you first set a to 20 and then initialize it to getA() - which is just as illegal as if you would have done it inside a function.
回答2:
Order matters.
static fields, block executes based on the order they placed in source code.
Move the declaration up . So that It can available to below blocks.
来源:https://stackoverflow.com/questions/22198527/cannot-reference-a-field-before-it-is-defined-error