【发布时间】:2014-05-03 05:20:27
【问题描述】:
考虑以下场景:
代码: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:1 会抛出错误,如果 代码:2 是真的吗?
【问题讨论】:
标签: java static scope static-variables static-block