62,623
社区成员
发帖
与我相关
我的任务
分享
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);//2
Table() {//4
System.out.println("Table()");
b2.f(1);//5
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);//3
}
class Cupboard {
Bowl b3 = new Bowl(3);//9 //14 //19
static Bowl b4 = new Bowl(4);//7
Cupboard() {//10 //15 //20
System.out.println("Cupboard()");
b4.f(2);//11 //16 //21
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);//8
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println(
"Creating new Cupboard() in main");//12
new Cupboard();//13
System.out.println(
"Creating new Cupboard() in main");//17
new Cupboard();//18
t2.f2(1);//22
t3.f3(1);//23
}
static Table t2 = new Table();// 1
static Cupboard t3 = new Cupboard();//6
}
/**
*Bowl允许我们检查一个类的创建过程,而Table和Cupboard能创建散布于类定义中的Bowl的static成员。
*注意在static定义之前,Cupboard先创建了一个非static的Bowl b3。它的输出结果如下:
//来源,JAVA编程思想第4章 初始化和清除
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)
*
*
*
*
*
*
*
*
*
*/