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(); } ///:~ 输出结果为: 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)
1.首先运行static Table t2= new Table();定义一个Table型的对象t2,在Table内又先初始化 b1, 此时调用Bowl方法,输出Bowl(1);然后回到Table内初始化b2,再次调用Bowl,输出Bowl(2)。将Table 内的static初始化完后才开始初始化Table类中的Table方法,输出Table();接着执行b2.f(1), 输出f(1); 2.然后运行static Cupboard t3=new Cupboard(); 定义了一个Cupboard型的对象t3,再Cupboard内首先初始化b4;调用Bowl方法,输出Bowl(4),然后回到Cupboard内初始化b5,输出Bowl(5),接着初始化b3, 输出Bowl(3),接着输出Cupboard().然后调用f方法输出f(2); 3.接着开始执行main方法, 首先输出Creating new Cupboard() in main , 这是碰到new Cupboard();进入类Cupboard,先运行Bow b3=new Bowl(3), 输出Bowl(3), 接着输出Cupboard(),然后运行b2.f(2),输出f(2). 4.然后回到main方法内,首先输出Creating new Cupboard() in main,又碰到了new Cupboard(), 如上所述,输出Bowl(3),输出Cupboard(), 输出f(2). 5.下面就是运行t2.f2(1); 因为前面已经定义好了t2,此时直接调用t2 的f2方法就行,再Table内调用f2方法输出f2(1);运行t2.f3(1)也一样,调用Cupboard内的方法f2就输出了f3(1).