java多態的理解

來源:互聯網
上載者:User

標籤:順序   ring   size   alt   package   必須   參考型別   方法   class   

對於java中,非常重要的一個概念就是多態,但多態裡面的很多坑是很容易被忽視的,在此,我總結一下我遇到的坑。

1、對於域和靜態方法,是不存在多態的。demo如下:

package com.zh.model;public class Test2 {    public int index = 0;    public int getIndex() {        return index;    }    public static void main(String[] args) {        Test2 test2 = new Child();        System.out.println("test2.index="+test2.index+"  test2.getIndex()="        +test2.getIndex());        Child child = new Child();        System.out.println("child.index="+child.index+"  child.getIndex()="                +child.getIndex());    }}class Child extends Test2{    public int index = 1;    public int getIndex() {        return index;    }    public int getSuperIndex(){        return super.index;    }}

輸出結果為:

 2、父類沒有預設構造器,有帶參數的構造器時,子類必須顯式編寫調用父類構造器的語句super(。。。)

,如果沒有顯式使用super關鍵字則會報錯。

3、使用父類類型的引用指向子類的對象時多態載入順序:即  在main‘方法中執行Parent parent = new Children();

先載入根基類中static初始化----根基類的子類static初始化----。。。。-----該類的static初始化-----對象中所有基本類型初始化為預設值,參考型別設為null-----調用父類構造器----調用子類構造器

 class Parent {
public static int parent = 1;
static {
System.out.println(parent);
}
public Parent() {
System.out.println("Parent");
}


public static void main(String[] args) {
Parent aaa = new Children();
}
}
class Children extends Parent{
public static int children = 2;
static {
System.out.println(children);
}
public Children() {
System.out.println("Children");
}
}

輸出:

 

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.