一个Java程序的运行流程,大家帮忙分析一下思路,共享,感谢
//everrr c4.StaticInitialization
/* 初学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);
Table() {
System.out.println( "Table() ");
b2.f(1);
}
void f2(int marker) {
System.out.println( "f2( " + marker + ") ");
}
static Bowl b2 = new Bowl(2);
}
class Cupboard {
Bowl b3 = new Bowl(3);
static Bowl b4 = new Bowl(4);
Cupboard() {
System.out.println( "Cupboard() ");
b4.f(2);
}
void f3(int marker) {
System.out.println( "f3( " + marker + ") ");
}
static Bowl b5 = new Bowl(5);
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println( "Creating new Cupboard() in main ");
new Cupboard();
System.out.println( "Creating new Cupboard() in main ");
new Cupboard();
t2.f2(1);
t3.f3(1);
}
static Table t2 = new Table();
static Cupboard t3 = new Cupboard();
} //everrr.
这个是输出结果:
123456789101112131415161718192021
Bowl(1) //static的初始化是最先进行的,所以static Table t2 = new Table (); 先运行,创建Table类的对象,于是Table
//类里的2个static的初始化运行,并且先于f2()和构造函数,于是static的b1 和b2最先被创建
Bowl(2)
Table() //在static的b1和b2被创建并有Bowl()输出之后,Table的构造函数运行,输出Tabel(),并出数f(1)
f(1) //此时,和static Table t2 = new Table();相关的动作结束
Bowl(4) //static Cupboard t3 = new Cupboard();创建Cupborard类的对象t3, 于是class Cupboard里的
//static初始化优先运行,输出b4和b5,