日期:2014-05-20  浏览次数:20620 次

请问:java编程思想第三版第111页的程序中的初始化问题
这个程序如下所示:

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();



输出结果是:

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)


我对着这个结果还有疑惑,要问大家,关于“静态初始化”,它的初始化顺序到底是什么???

对于这个程序而言,从输出结果看,是先从static Table t2 = new Table(); 这一行代码开始的,这是为什么呢???

为什么不从其它地方开始???




------解决方案--------------------
没有用new ExplicitStatic()来创建该类的对象,
“对于非继承类,是先从public类的static成员开始初始化起的,且static成员只初始化一次”
Cup x = new Cup(13); x不是static的,只有在创建对象时才会先于构造器被加载。