Thinking in Java之衍生类和基础类的初始化顺序
Posted WesTward
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thinking in Java之衍生类和基础类的初始化顺序相关的知识,希望对你有一定的参考价值。
《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之衍生类和基础类的初始化顺序的主要内容,如果未能解决你的问题,请参考以下文章
thinking in java 之Reference类的使用
thinking in java之Collections工具类的使用
Thinking in Java Reading Note(9.接口)
类的特殊获取方式——《Thinking in Java》随笔008