class Meal
  {
     Meal(){System.out.println("Meal()");}
  }class Bread
  {
     Bread(){System.out.println("Bread()");}
   }class Cheese
  {
     Cheese(){System.out.println("Cheese()");}
   }class Lettuce
  {
     Lettuce(){System.out.println("Lettuce()");}
   }class Lunch extends Meal
  {
     Lunch(){System.out.println("Lunch()");}
  }class PortableLunch extends Lunch
  {
    PortableLunch(){System.out.println("PortableLunch()");}
  }class Sandwich extends PortableLunch
  {
    Bread b=new Bread();
    Cheese c=new Cheese();
    Lettuce l=new Lettuce();
    Sandwich() {System.out.println("Sandwinch()");}
    public static void main(String[] args)
      {
        new Sandwich();
      }
  }
我认为的结果:
Meal()
Lunch()
PortableLunch()
Sandwich()
Bread()
Cheese()
Lettuce()
可是答案是:
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()不知道为什么会是这样,请求热心人士帮助,谢谢

解决方案 »

  1.   

    这是初始化顺序问题. 但你 构造 new Sandwich() 时候.首先调用它的基类. 也就是输出
    Meal()
    Lunch()
    PortableLunch()
    这个你已经知道.然后. 你要初始化  Sandwich 类里的static 成员.(这个你程序里没有.跳过)
    -->初始化  非static 成员(即  Bread b=new Bread();Cheese c=new Cheese();Lettuce l=new Lettuce(); ) -->然后你才可以构建  你的对象
      

  2.   

    这个程序的执行过程可能是这样的,最先从main中执行new Sandwich();这就要调用构造函数,当然最先调用的是继承的祖先的构造函数,在执行class Sandwich 构造函数Sandwich()之前,那些变量会在调用任何方法之前得到初始化——甚至在构造函数调用之前.可能是这个原因,呵呵,我也是初学的,如果错了不要见笑啊.
      

  3.   

    难道是现在兴起了新的一股学习java的热潮?今天好多人问这种问题呀
      

  4.   

    我贴个给楼主看看:
    ===============
    package pk;class A{
    static A a1=new A(111);
    public A(int i){
    System.out.println("new Father()"+i);
    }
    {
    System.out.println("father block");
    }
    static {
    System.out.println("static father block");
    }
    }public class Init extends A{
    static Init a2=new Init(222);
    Init(){
    this(12);
    System.out.println("new son()");
    }
    Init(int x){
    super(0);
    System.out.println("new son(int)");
    }
    {
    System.out.println("son block");
    }
    static {
    System.out.println("static son block");
    }
    public static void main(String[] args){
    new Init();
    }
    }
      

  5.   

    to  supjia() :static的调用是在父类的构造函数调用之前吧?
      

  6.   

    我贴个给楼主看看:
    ===============
    package pk;class A{
    static A a1=new A(111);
    public A(int i){
    System.out.println("new Father()"+i);
    }
    {
    System.out.println("father block");  //请问这类里的方法名怎么会没
    }                                             //啊,而且还运行得了哦,不知
    static {                                      //不知道这个是如何理解的,
    System.out.println("static father block");//谁能告诉我这个原理,谢
    }
    }public class Init extends A{
    static Init a2=new Init(222);
    Init(){
    this(12);
    System.out.println("new son()");
    }
    Init(int x){
    super(0);
    System.out.println("new son(int)");
    }
    {
    System.out.println("son block");
    }
    static {
    System.out.println("static son block");
    }
    public static void main(String[] args){
    new Init();
    }
    }