码迷,mamicode.com
首页 > 编程语言 > 详细

Thinking in Java之衍生类和基础类的初始化顺序

时间:2016-03-28 16:45:54      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:

《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成员,创建衍生类,初始化顺序:一直向上,从根类开始,初始化根类成员,然后根类构造器;然后向下,次根类成员,次根类构造器,以此类推,一直到衍生类本身。

Thinking in Java之衍生类和基础类的初始化顺序

标签:

原文地址:http://www.cnblogs.com/westward/p/5329509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!