1. 程式人生 > >JAVA & .NET創建對象構造函數調用順序

JAVA & .NET創建對象構造函數調用順序

person pub ron 沒有 models nes end 構造函數 init

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創建對象構造函數調用順序