Java中static塊,構造塊,構造函數的執行順序


public class Father {
    static {
        System.out.println("Father靜態塊");
    }

    {
        System.out.println("Father構造塊");
    }

    public Father() {
        System.out.println("Father構造函數");
    }

    void func1() {
        System.out.println("Father方法 1");
    }

    public static void main(String[] args) {
        Father father = new Son();
        father.func1();
        ((Son) father).func2();
//        father.func2();
    }

}

class Son extends Father {
    static{
        System.out.println("Son靜態塊");
    }

    {
        System.out.println("Son構造塊");
    }

    public Son() {
        System.out.println("Son構造函數");
    }

    @Override
    void func1() {
        System.out.println("Son方法 1");
    }

    void func2() {
        System.out.println("Son方法 2");
    }

}

結果:

父類靜態塊 -> 子類靜態塊 -> 父類構造塊 -> 父類構造函數 -> 子類構造塊 -> 子類構造函數

 

在main方法中:

  ①father對象指向的是new 出來的Son對象,且Son對象繼承Father對象並且@override 重寫(覆蓋)了父類的func1() 方法,即這樣的話,子類對象賦給父類對象,父類對象調用父類中被子類重寫的方法時,實際是調用了子類中已經重寫過的方法,即:

Father f = new Son();

f.func1();
Son s = new Son();

s.func1();

兩者都是一樣的,都是指向new 出來的Son 對象。

  ②因為father對象指向new 出來的Son 對象,所以可以將father對象強制轉換成 Son對象,這樣就可以調用 Son對象的func2()方法,因為兩者在內存上就是一樣的存在。

  ③錯誤,father對象不存在func2() 方法,只能強制轉換成 Son對象,即可調用。

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM