class Bowl {   Bowl(int er) { 
    System.out.println("Bowl(" + er + ")"); 
  } 
  void f(int er) { 
    System.out.println("f(" + er + ")"); 
  } 
} class Table { 
  static Bowl b1 = new Bowl(1); 
  Table() { 
    System.out.println("Table()"); 
    b2.f(1); 
  } 
  void f2(int er) { 
    System.out.println("f2(" + er + ")"); 
  } 
  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 er) { 
    System.out.println("f3(" + er + ")"); 
  } 
  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) 问:为什么不先打印Creating new Cupboard() in main 这句话啊?? 在虚拟机中是如何执行的啊?
能不能讲下执行的过程啊?

解决方案 »

  1.   

     static Table t2 = new Table();  
      static Cupboard t3 = new Cupboard();  类先初始化静态属性,静态代码块,然后再调用静态方法非静态方法,还有先出示化非静态属性,非静态代码块,然后是构造器,然后才是非静态的方法。
      

  2.   

    类先初始化静态属性,静态代码块,然后再调用静态方法 
    =============================================
    是不是这样啊 你试试看下面这个代码
    我试的结果是 静态域和静态块谁在前面先执行谁 静态方法好像没执行public class Test{ 
      static void f(){
        System.out.println("static f()");
        System.exit(0);
      }  static{
        System.out.println("static block");
    }  static Aclass a=new Aclass();

    class Aclass{
      Aclass(){
        System.out.println("static field");
      }
    }
      

  3.   

    static Aclass a=new Aclass(); 这样写不好吧