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

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

执行顺序为:

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

⚠️ JAVA中加载类时会调用类的静态代码块

try {
    Class.forName("models.Chinese");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

执行结果如下:

person static block
chinese static block
chinese static block 2

.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先执行当前类中的静态代码块,然后先执行基类中的实例构造函数;

posted @ 2019-02-24 11:49  雪飞鸿  阅读(498)  评论(0编辑  收藏  举报