考虑以下场景:
代码:1
public class StaticDemo {
static{
b=5;
System.out.println("Static B:"+b);/*Compilation error:"Cannot reference a field before it is defined"*/
}
static int b;
static{
System.out.println("B:"+b);
}
public static void main(String[] args) {
}
}
将代码注释如下,没有错误,并且显示了以下输出。
代码:2
public class StaticDemo {
static{
b=5;
//System.out.println("Static B:"+b);
}
static int b;
static{
System.out.println("B:"+b);
}
public static void main(String[] args) {
}
}
输出-
B:5
如果执行基于静态变量或块的写入顺序。
为什么初始化( )没有抛出编译错误
b=5
,如代码:2所示。如果 Code:2 为真,请解释为什么 Code:1 会抛出错误?