服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java与c#的构造函数执行顺序的不同之处

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.");
}
}

结果是

to construct parent.

to construct delegatee.

to construct child.

而c#的构造函数执行顺序是:先引用对象,在父类,再子类.

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#是同层依赖优先于跨层依赖.

扫描关注微信公众号