Java中的多態

來源:互聯網
上載者:User

標籤:引用   images   ++   style   類對象   運行   new   int   block   

  1. 子類和父類定義了一模一樣的欄位和方法,將會出現什麼樣的結果。運行以下代碼,看看會出現什麼樣的結果。
    public class ParentChildTest {    public static void main(String[] args) {        Parent parent=new Parent();        parent.printValue();        Child child=new Child();        child.printValue();                parent=child;        parent.printValue();                parent.myValue++;        parent.printValue();                ((Child)parent).myValue++;        parent.printValue();            }}class Parent{    public int myValue=100;    public void printValue() {        System.out.println("Parent.printValue(),myValue="+myValue);    }}class Child extends Parent{    public int myValue=200;    public void printValue() {        System.out.println("Child.printValue(),myValue="+myValue);    }}

    程式:

  2.  

  3. 程式原因分析:當子類與父類擁有一樣的方法,並且讓一個父類變數引用一個子類對象時,到底調用哪個方法,由對象自己的“真實”類型所決定,這就是說:對象是子類型的,它就調用子類型的方法,是父類型的,它就調用父類型的方法。
  4. 對於多態,可以總結它為:

      一、使用父類類型的引用指向子類的對象;

      二、該引用只能調用父類中定義的方法和變數;

      三、如果子類中重寫了父類中的一個方法,那麼在調用這個方法的時候,將會調用子類中的這個方法;(動態串連、動態調用)

      四、變數不能被重寫(覆蓋),”重寫“的概念只針對方法,如果在子類中”重寫“了父類中的變數,那麼在編譯時間會報錯。

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.