虽然用Java一段时间了,不过还是第一次听到 instance initializer (实例初始化块)
以前知道有一个 static initializer (静态初始化块)会在类加载的时候执行。
instance initializer 则是在构造函数执行过程中的某一时刻执行。见代码:
// LoadOrder.java
public class LoadOrder {
private Property _property = new Property();
{ // instance initializer
System.out.println("{ Load Block 1 }");
}
static { // static initializer
System.out.println("{ static 1 }");
}
public LoadOrder() {
System.out.println("LoadOrder()");
_property = new Property(this);
}
{
System.out.println("{ Load Block 2 }");
}
static {
System.out.println("{ static 2 }");
}
public static void main(String[] args) {
System.out.println("==== main() 1 ====");
new LoadOrder();
System.out.println("==== main() 2 ====");
new LoadOrder();
Property referee = new Property();
}
}
class Property {
public Property() {
System.out.println("Property()");
}
public Property(Object owner) {
System.out.println("Property(Object)");
}
}
// EOF
运行结果如下:
{ static 1 }
{ static 2 }
==== main() 1 ====
Property()
{ Load Block 1 }
{ Load Block 2 }
LoadOrder()
Property(Object)
==== main() 2 ====
Property()
{ Load Block 1 }
{ Load Block 2 }
LoadOrder()
Property(Object)
Property()
//EOF
0 comments:
Post a Comment