程序摘取自《Java编程思想第四版》
class Bowl {
Bowl(int marker){
System.out.println("Bowl(" + marker+")");
}
void f(int marker){
System.out.println("f)" + marker + ")");
}
}
class Table {
static Bowl b1 = new Bowl(1);
static{
b1 = new Bowl(3);
}
Table(){
System.out.println("Table()");
}
void f2(int marker){
System.out.println("f2(" + marker + ")");
b2.f(marker);
}
static Bowl b2 = new Bowl(2);
}
class Cupborad {
Bowl b3 = new Bowl(3);
static Bowl b4 = new Bowl(4);
Cupborad(){
System.out.println("Cupborad()");
b4.f(2);
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);
}
public class Test {
public static void main(String[] args) {
System.out.println("Creating new Cupborad() in main()");
new Cupborad();
System.out.println("Creating new Cupborad() in main()");
new Cupborad();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupborad t3 = new Cupborad();
}
运行结果如下:
Bowl(1)
Bowl(3)
Bowl(2)
Table()
Bowl(4)
Bowl(5)
Bowl(3)
Cupborad()
f(2)
Creating new Cupborad() in main()
Bowl(3)
Cupborad()
f(2)
Creating new Cupborad() in main()
Bowl(3)
Cupborad()
f(2)
f2(1)
f(1)
f3(1)
———————结果分析———————————
首先调用main方法,所以会加载类Test,加载类Test时按照顺序初始化静态变量(首先初始化t2,其次初始化t3)
初始化t2时,加载类Table,加载类Table时按照顺序初始化静态变量(b1->b1->b2)初始化b1时,调用Bowl的构造函数,打印Bowl(1),static模块再次为b1赋值打印Bowl(3),初始化b2时,打印Bowl(2),再次调用Table构造函数打印Table()
初始化t3时,顺序初始化静态变量b4/b5分别打印Bowl(4)、Bowl(5);接着初始化非静态变量b3打印Bowl(3),然后调用Cupborad构造函数打印Cupborad() 打印f(2)
调用main方法,打印Creating new Cupborad() in main()
再次调用new Cupborad()时,此时首先初始化非静态变量b3打印Bowl(3),然后打印Cupborad()打印f(2)
再次打印Creating new Cupborad() in main()
再再次调用new Cupborad()时,此时首先初始化非静态变量b3打印Bowl(3),然后打印Cupborad(),打印f(2)
执行t2.f2(1),打印f2(1)、f(1)
执行t3.f3(1),打印f3(1)