java构造顺序_java 构造函数调用顺序

当一个复杂的对象被构造时,它的构造函数按下面的顺序被调用(that the order of constructor calls for a complex object is as follows)

1.其基类(base-class)的构造函数被调用,这个步骤以递归的方式重复,所以最底层(the root of

hierarchy)的构造函数首先被执行,然后是它上一层派生类(the next-derived class)...直到最顶层的派生类(the

most-derived class).

The base-class constructor is called. This

step is repeated recursively such that the root of the hierarchy is

constructed first, followed by the next-derived class, etc., until the

most-derived class is reached.)

2.如果有包含关系(composition),那么它的成员对象按照声明的顺序被构造.

Member initializers are called in the order of declaration.

3.派生类构造函数的内容(body)被执行.

The body of the derived-class constructor is called.

一个实例:

classCake{

Cake(){System.out.println("Cake()");}

}classMeal {

Meal() { System.out.println("Meal()"); }

}classBread {

Bread() { System.out.println("Bread()"); }

}classCheese {

Cheese() { System.out.println("Cheese()"); }

}classLettuce {

Lettuce() { System.out.println("Lettuce()"); }

}classLunchextendsMeal {

Lunch() { System.out.println("Lunch()"); }

}classPortableLunchextendsLunch {//if make derived-class object as the menber of the base-class will lead a infinite//loop and program will stop because of the memory consumed//private Sandwich s=new Sandwich();privateCake a=newCake();

PortableLunch() { System.out.println("PortableLunch()");}

}publicclassSandwichextendsPortableLunch

{privateBread b=newBread();privateCheese c=newCheese();privateLettuce l=newLettuce();publicSandwich() {

System.out.println("Sandwich()");

}publicstaticvoidmain(String[] args)  {newSandwich();

}

}

输出:

Meal()

Lunch()

Cake()

PortableLunch()

Bread()

Cheese()

Lettuce()

Sandwich()

main()函数中要构造一个Sandwich的对象,调用(并不是执行)它基类PortableLunch的构造函数,PortableLunch又递

归的调用,然后是Meal,Meal是继承的最底层的基类(不算Object)所以它的构造函数首先被执行,然后按次序返回到Lunch,

PortableLunch,但在PortableLunch的构造函数被执行之前,它的成员对象Cake

a先按照声明的顺序被构造.然后执行PortableLunch(),接着是Sandwich的成员对象,最后是Sandwich().

注:被注释掉的代码,将base-class的对象作为derive-class的成员对象,这样会递归无法结束,最后程序因堆栈耗尽而结束(Exception in  thread main java.lang.StackOverflowError).

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1134115(转)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值