标签:
《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