java類中元素初始化順序詳解_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

public class Test4 {
    @Test
    public void test(){
        child child = new child();
    }
}

class parent{
    public static String parentStaticField = "父類靜態變數";
    public String parentNormalField ="父類普通變數";
    static {
        System.out.println(parentStaticField);
        System.out.println("父類靜態塊");
    }

    {
        System.out.println(parentNormalField);
        System.out.println("父類普通塊");
    }

    public parent(){

        System.out.println("父類構造方法");
    }
}

class child extends parent{
    public static String childStaticField = "子類靜態變數";
    public String childNormalField ="子類普通變數";
    static {
        System.out.println(childStaticField);
        System.out.println("子類靜態塊");
    }

    {
        System.out.println(childNormalField);
        System.out.println("子類普通塊");
    }

    public child(){
        System.out.println("子類構造方法");
    }
}


輸出:

複製代碼 代碼如下:

父類靜態變數
父類靜態塊
子類靜態變數
子類靜態塊
父類普通變數
父類普通塊
父類構造方法
子類普通變數
子類普通塊
子類構造方法

執行過程:

1、當執行到new child時,裝載器尋找已經編譯的child類的代碼(也就是child.class檔案)。在裝載的過程中,裝載器注意到它有一個基類,於是它再裝載基類。不管你創不建立基類對象,這個過程總會發生。如果基類還有基類,那麼第二個基類也會被裝載,依此類推。

2、執行根基類的static初始化,然後是下一個衍生類別的static初始化,依此類推。這個順序非常重要,因為衍生類別的“static初始化”有可能要依賴基類成員的正確初始化。

3、當所有必要的類都已經裝載結束,建立child類對象。

4、child類存在父類,則調用父類的建構函式,可以使用super來指定調用哪個建構函式。

  基類的構造過程以及構造順序,同衍生類別的相同。首先基類中各個變數按照字面順序進行初始化,然後執行基類的建構函式的其餘部分。

5、對子類成員資料按照它們聲明的順序初始化,執行子類建構函式的其餘部分。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.