45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:Java构造函数的调用顺序的详细介绍

Java构造函数的调用顺序的详细介绍

2016-08-25 10:17:45 来源:www.45fan.com 【

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{
//ifmakederived-classobjectasthemenberofthebase-classwillleadainfinite
//loopandprogramwillstopbecauseofthememoryconsumed

//privateSandwichs=newSandwich();
privateCakea=newCake();
PortableLunch(){System.out.println(
"PortableLunch()");}
}


publicclassSandwichextendsPortableLunch
{

privateBreadb=newBread();
privateCheesec=newCheese();
privateLettucel=newLettuce();

publicSandwich(){
System.out.println(
"Sandwich()");
}


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

本文地址:http://www.45fan.com/a/question/67341.html
Tags: 函数 Java 构造
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部