Java對象初始化順序

在實例化對象前,若是沒有加載過相應的類信息,那麼會首先加載類,而後才實例化對象。函數

在這種狀況下,順序爲:測試

a. 加載類spa

  1. 爲父類靜態屬性分配內存並賦值 / 執行父類靜態代碼段 (靜態代碼塊和靜態成員,前後按照實際的代碼順序,進行初始化)
  2. 爲子類靜態屬性分配內存並賦值 / 執行子類靜態代碼段 (按代碼順序)

b. 建立對象code

  1. 爲父類實例屬性分配內存並賦值 / 執行父類非靜態代碼段 (按代碼順序)
  2. 執行父類構造器
  3. 爲子類實例屬性
  4. 執行子類構造函數
加載類的過程只會執行一次,所以,今天成員的初始化也只有一次,在此只會,再進行子類對象初始化,只會執行普通成員和構造函數的初始化。
用代碼進行測試:
public class Father {
    Another a = new Another("father 普通成員");
    static Another a1 = new Another("father 靜臺成員");
    static {
        Another a2 = new Another("father static block");
    }

    public Father(){
        System.out.println("執行father構造");
    }
}

子類:對象

public class Son extends Father{

    static Another aa1 = new Another("son 靜態成員");
    Another a2 = new Another("son 普通成員");

    static{
        Another a2 = new Another("son 靜態代碼塊");
    }
    public Son(){
        System.out.println("執行Son構造函數");
    }

}

 

測試類:blog

public class Test {



    static {
        System.out.println("靜態代碼塊執行");
    }


    public static void main(String[] args) {
        Son tn = new Son();

    }
}

輸出爲:內存

靜態代碼塊執行
father 靜臺成員
father static block
son 靜態成員
son 靜態代碼塊
father 普通成員
執行father構造
son 普通成員
執行Son構造函數

參考:https://www.zhihu.com/question/49196023/answer/114859346io

相關文章
相關標籤/搜索