JAVA重載(overload)和覆蓋(override)中你所不知道的陷阱

來源:互聯網
上載者:User

大家都知道重載是指在同一個類中,定義了有相同名稱但是有不同參數類型的方法時,到底調用那一個方法會根據參數類型來選擇.我們來看下面這個例子:

public class ParentClass {}public class ChildClass extends ParentClass{}public class Test {public void testOverLoad(ParentClass cls){System.out.println("It's ParentClass");}public void testOverLoad(ChildClass cls){System.out.println("It's ChildClass");}public static void main(String[] args) {Test test = new Test();ParentClass parentCls = new ParentClass();ParentClass childCls = new ChildClass();test.testOverLoad(parentCls);test.testOverLoad(childCls);}}

大家想想輸出的結果應該是什麼呢,答案是:
It's ParentClass
It's ParentClass
原因是決定方法重載是在編譯的時候發生,而不是在啟動並執行時候.在編譯的時候,parentCls和childCls的類型都是ParentClass.
覆蓋是指在父類和子類有相同名稱參數的方法,子類的方法覆蓋父類的方法.來看下面的例子:

public class ParentClass {    public String str1 = "Parent1";    public String str2 = "";    public  ParentClass(){        str2="Parent2";    }    public void func(){        System.out.println("ParentClass.func");    }    public String getStr2() {        return str2;    }}public class ChildClass extends ParentClass{    public String str1 = "Child1";    public String str2 = "";        public  ChildClass(){        str2="Child2";    }        public void func(){        System.out.println("ChildClass.func");    }    public String getStr2() {        return str2;    }}public class Test     public static void main(String[] args) {        ParentClass childCls = new ChildClass();        System.out.println(childCls.str1);        System.out.println(childCls.str2);        System.out.println(childCls.getStr2());        childCls.func();    }}

輸出的結果應該是什麼呢,答案是:
Parent1
Parent2
Child2
ChildClass.func
原因是對於方法的覆蓋發生在運行時,所以子類的方法被調用.而對於變數的覆蓋是在編譯的時候決定的,childCls在編譯的時候類型是ParentClass,所以對變數的直接存取得到的是ParentClass中定義的值.對於成員變數,編譯器會對父類和子類的所有成員變數都儲存一份拷貝.

聯繫我們

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