《Thinking in Java》书里的例子,我又稍微修改了下代码:

class Real{
    public Real(String index) {
        // TODO Auto-generated constructor stub
        System.out.println("Real()"+index);
    }
}
class Meal{
    Real r= new Real("Meal");
    Meal() {
        // TODO Auto-generated constructor stub
        System.out.println("Meal()");
    }
}
class Bread{
    Bread() {
        // TODO Auto-generated constructor stub
        System.out.println("Bread()");
    }
}
class Cheese{
    Cheese() {
        System.out.println("Cheese()");
    }
}
class Lettuce{
    Lettuce() {
        // TODO Auto-generated constructor stub
        System.err.println("Lettuce()");
    }
}
class Lunch extends Meal{
    Real r= new Real("Lunch");
    Lunch(){
        System.out.println("Lunch()");
    }
}
class PortableLunch extends Lunch{
    Real r= new Real("PortableLunch");
    PortableLunch(){
        System.out.println("PortableLunch()");
    }
}
public class Sandwich extends PortableLunch{
    Bread b= new Bread();
    Cheese c= new Cheese();
    Lettuce l= new Lettuce();
    Sandwich(){
        System.out.println("Sandwich()");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Sandwich();
    }

}

output:


Real()Meal
Meal()
Real()Lunch
Lunch()
Real()PortableLunch
PortableLunch()
Bread()
Cheese()

Lettuce()
Sandwich()

总结:

如果衍生类和基础类都没有static成员,创建衍生类,初始化顺序:一直向上,从根类开始,初始化根类成员,然后根类构造器;然后向下,次根类成员,次根类构造器,以此类推,一直到衍生类本身。

 

自己摸索的demo:

package com.westward;

public class Demo19 extends Animal{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Demo19.main();");
    }

}
class Animal{
    public static Good good= new Good(); 
}
class Good{
    public Good() {
        System.out.println("Good()");
    }
}
/*
 * 在继承中,如果衍生类有main方法,main方法中并未创建实例,加载顺序也是先加载基础类的static成员。然后衍生类的static成员,然后面方法。
 * 一句话,如果需要加载衍生类的类类型,即class,那么无论是创建此类的实例还是调用此衍生类的static方法(包括main方法),都会先去加载基础类,并初始化static成员。
 * */

output:
Good()
Demo19.main();

posted on 2016-03-28 16:26  WesTward  阅读(605)  评论(0编辑  收藏  举报