java 父類子類成員變數,靜態變數,構造器建立先後順序

來源:互聯網
上載者:User

標籤:

關於java中父類子類,成員變數,靜態變數,構造器建立的先後順序,在面試中經常會問到該類型的問題

所以用以下代碼進行測試:





public class Test {    public static void main(String args[]) {        Father f = new Son();    }}class Father {    public Father() {        System.out.println("Father Construct");    }    static int fatherStatic=printFatherStatic();    int father=printFather();    static int printFatherStatic() {        System.out.println("print in father static mamber");        return 0;    }    static int printFather(){        System.out.println("print in father class mamber");        return 0;    }}class Son extends Father {    public Son() {        System.out.println("Son Construct");    }    static int sonStatic=printSonStatic();    int son=printSon();    static int printSonStatic() {        System.out.println("print in son static mamber");        return 0;    }    static int printSon(){        System.out.println("print in son class mamber");        return 0;    }}

 



運行結果為:

print in father static mamber
print in son static mamber
print in father class mamber
Father Construct
print in son class mamber
Son Construct

 

總結一下,得出以下結論:

建立的先後順序為:父類的靜態變數->子類的靜態變數->父類的成員變數->父類的構造方法->子類的成員變數->子類的構造方法

總的來說,首先建立靜態方法,然後建立父類的成員變數和構造方法,再建立子類的成員變數和構造方法

 

java 父類子類成員變數,靜態變數,構造器建立先後順序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.