class Bowl {
  Bowl(int er) {
    System.out.println("Bowl(" + er + ")");
  }
  void f1(int er) {
    System.out.println("f1(" + er + ")");
  }
}class Table {
  static Bowl bowl1 = new Bowl(1);
  Table() {
    System.out.println("Table()");
    bowl2.f1(1);
  }
  void f2(int er) {
    System.out.println("f2(" + er + ")");
  }
  static Bowl bowl2 = new Bowl(2);
}class Cupboard {
  Bowl bowl3 = new Bowl(3);
  static Bowl bowl4 = new Bowl(4);
  Cupboard() {
    System.out.println("Cupboard()");
    bowl4.f1(2);
  }
  void f3(int er) {
    System.out.println("f3(" + er + ")");
  }
  static Bowl bowl5 = 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();
    table.f2(1);
    cupboard.f3(1);
  }
  static Table table = new Table();
  static Cupboard cupboard = new Cupboard();
}为什么执行到new Cupboard() 后会再执行Bowl bowl3 = new Bowl(3) 。本来以为输出Creating new Cupboard() in main后,接着是输出Cupboard()和f1(2),没想到中间插着一个Bowl(3)。 
输出结果:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)

解决方案 »

  1.   

    静态属性而言,并没有什么特别的,这种问题,用debug一调试就立马明白了,你的问题这么不简洁,有多少人能耐心看下去呢
      

  2.   

    运行到new Cupboard();进入类Cupboard时为什么会再次运行Bowl bowl3 = new Bowl(3);而运行cupboard.f3(1);时为什么不会再次运行Bowl bowl3 = new Bowl(3);求解释。
      

  3.   


    调用new Cupboard()和cupboard.f3(1)运行机制有什么区别
      

  4.   

    一个是调用静态方法来创建对象,一个是调用方法,区别大了
    详情看看Thinking in JAVA里面的第96页
      

  5.   


    Creating new Cupboard() in main
    Bowl(3)
    Cupboard()
    f1(2)
    Creating new Cupboard() in main
    Bowl(3)因为你的main中 new Cupboard();产生了一个新的对象
    Bowl bowl3 = new Bowl(3);这句代码必定被执行一次的嘛
    也就造成了输出
    Creating new Cupboard() in main
    Bowl(3)
    两个静态的就不执行了
    输出也没问题啊
      

  6.   

    楼主的代码应该是  thinking in. Java中的吧!  前几天刚看过  这是静态
     与非静态的初实化问题  后面有总结的!