首页 > 编程语言 > 详细

JAVA & .NET创建对象构造函数调用顺序

时间:2019-02-24 12:16:57      阅读:147      评论:0      收藏:0      [点我收藏+]

JAVA

定义Person类

package models;
?
public class Person {
    public Person() {
        System.out.println("person constructor");
    }
?
    {
        System.out.println("person init block");
    }
?
    static {
        System.out.println("person static block");
    }
}

 

定义Chinese类

package models;
?
public class Chinese extends Person {
    public Chinese() {
//        super();
        System.out.println("chinese constructor");
    }
?
    {
        System.out.println("chinese init block");
    }
?
    {
        System.out.println("chinese init block2");
    }
?
    static {
        System.out.println("chinese static block");
    }
?
    static {
        System.out.println("chinese static block 2");
    }
}

?

创建Chinese类实例

public class Program {
    public static void main(String[] args) {
        new Chinese();
    }
}

 

输出结果如下:

person static block
chinese static block
chinese static block 2
person init block
person constructor
chinese init block
chinese init block2
chinese constructor

执行顺序为:

基类静态初始化块——当前类静态初始化块——基类初始化块——基类构造函数——当前类初始化块——当前类构造函数

.NET

与JAVA相比,.NET中没有初始化块及静态初始化块

定义类型如下:

class Person
{
    public Person()
    {
        Console.WriteLine("person constructor");
    }
?
    static Person()
    {
        Console.WriteLine("person static constructor");
    }
}
?
class Chinese : Person
{
    public Chinese()
    {
        Console.WriteLine("chinese constructor");
    }
?
    static Chinese()
    {
        Console.WriteLine("chinese static constructor");
    }
}

?

创建对象:

class Program
{
    static void Main(string[] args)
    {
        new Chinese();
    }
}

 

输出结果如下:

chinese static constructor
person static constructor
person constructor
chinese constructor

执行顺序为:

当前类静态构造函数——基类静态构造函数——基类构造函数——当前类构造函数

小结

JAVA与.NET创建对象时都是先执行静态代码块后执行非静态代码块;

JAVA先执行基类中的静态及非静态代码块;

.NET先执行基类中的静态代码块,先执行当前类中的实例构造函数;

JAVA & .NET创建对象构造函数调用顺序

原文:https://www.cnblogs.com/Cwj-XFH/p/10425739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!