Java: 先执行父类的构造函数,然后是引用对象的构造函数(必须有new声明实际类型),然后是自己的构造函数。
public class Test
{
public static void main(String[] args)
{
Child child = new Child();
}
}
class Parent
{
Parent()
{
System.out.println("to construct Parent.");
}
}
class Child extends Parent
{
Child()
{
System.out.println("to construct Child.");
}
Delegatee delegatee = new Delegatee();
}
class Delegatee
{
Delegatee()
{
System.out.println("to construct Delegatee.");
}
}
结果是
而C#的构造函数执行顺序是:先引用对象,在父类,再子类.to construct Parent.
to construct Delegatee.
to construct Child.
using System;
namespace ConsoleApplication1
{
public class Test
{
public static void Main(String[] args)
{
Child child = new Child();
}
}
class Parent
{
public Parent()
{
Console.WriteLine("to construct parent");
}
}
class Child : Parent
{
public Child()
{
Console.WriteLine("to construct Child.");
}
Delegatee delegatee = new Delegatee();
}
class Delegatee
{
public Delegatee()
{
Console.WriteLine("to construct Delegatee.");
}
}
}
结果是
to construct Delegatee.
to construct Child.
to construct Parent.
总结:
被依赖的先构造,依赖于人的后构造。JAVA 是跨层依赖优先于同层依
赖构造,而C#是同层依赖优先于跨层依赖.
上一篇: [学习笔记]Thinking in Java (the 2nd edition) Study Note
下一篇: Soap 结 构 初 识
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!



