JAVA 与C#构造函数执行顺序的不同之处.
类别: JAVA教程
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#是同层依赖优先于跨层依赖.
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#是同层依赖优先于跨层依赖.
- 上一篇: Java性能
- 下一篇: 用java实现外部调用exe文件
-= 资 源 教 程 =-
文 章 搜 索