- 作者:zhaozj
- 发表时间:2020-12-23 10:36
- 来源:未知
class Bowl { Bowl(int marker) { ---------------------3,5构造 System.out.println("Bowl(" + marker + ")"); } void f(int marker) { ----------------------7,被table调用 System.out.println("f(" + marker + ")"); }}
class Table { static Bowl b1 = new Bowl(1); -----------------2,构造之前,也先static变量 Table() { -----------------6,变量已全部构造完成,执行构造函数 System.out.println("Table()"); b2.f(1); -----------------调用bow的f() } void f2(int marker) { System.out.println("f2(" + marker + ")"); } static Bowl b2 = new Bowl(2); ------------------4,第二个static变量的构造}
class Cupboard { Bowl b3 = new Bowl(3); -------------------11,static构造完后,构造非static成员 static Bowl b4 = new Bowl(4); -----------------9,先static成员构造 Cupboard() { ----------------12,成员已经构造好,执行构造函数 System.out.println("Cupboard()"); b4.f(2); --------------13,调用bow的f() } void f3(int marker) { System.out.println("f3(" + marker + ")"); } static Bowl b5 = new Bowl(5); ----------------10,按次序构造static成员}
public class StaticInitialization { public static void main(String[] args) { System.out.println( "Creating new Cupboard() in main"); -----------14,成员已经构造好,执行main函数体,首先执行此句 new Cupboard(); ------------------15,构造临时Cupboard对象 System.out.println( "Creating new Cupboard() in main"); new Cupboard(); t2.f2(1); t3.f3(1); } static Table t2 = new Table(); -------------------1,先static变量 static Cupboard t3 = new Cupboard();-----------------8,继续构造static成员}
运行结果如下Bowl(1)Bowl(2)Table()f(1)Bowl(4)Bowl(5)Bowl(3)Cupboard()f(2)Creating new Cupboard() in mainBowl(3)Cupboard()f(2)Creating new Cupboard() in mainBowl(3)Cupboard()f(2)f2(1)f3(1)===========================
##static型的变量或者方法叫做类变量和类方法类变量是在该类加载到内存的同时就进行初始化的而非static变量是在产生实例时进行初始化
因为要执行一个static方法main(),因此要先把该类加载到内存并同时进行static变量的初始化