初始化操作的一般顺序是(在加载类之后和首次使用之前):
静态(类)代码块按顺序出现在代码中,
对象代码块按顺序出现在代码中(初始化块和赋值)。
构造函数
当然我不会将构造函数和函数体引用为上面的代码块。
我不知道怎么样final static字段。 看起来它们遵循final static字段的规则,并且在声明之前它们不能被引用,尽管先前的注释它们在编译步骤初始化。 如果在编译错误之前引用它们:
Example.java:8: illegal forward reference
System.err.println("1st static block j=" + j);
也许final static字段可以初始化并编译到类文件中,但这不是一般规则,它们在声明之前仍然无法引用。
检查初始化顺序的示例代码:
class Example {
final static int j = 5;
{
System.err.println("1st initializer j=" + j);
}
static {
System.err.println("1st static block j=" + j);
}
static {
System.err.println("2nd static block j=" + j);
}
final static java.math.BigInteger i = new java.math.BigInteger("1") {
{
System.err.println("final static anonymous class initializer");
}
};
Example() {
System.err.println("Constructor");
}
static {
System.err.println("3nd static block j=" + j);
}
{
System.err.println("2nd initializer");
}
public static void main(String[] args) {
System.err.println("The main beginning.");
Example ex = new Example();
System.err.println("The main end.");
}
}
上面的代码片段打印:
1st static block j=5
2nd static block j=5
final static anonymous class initializer
3nd static block j=5
The main beginning.
1st initializer j=5
2nd initializer
Constructor
The main end.