java多態講解,java多態

來源:互聯網
上載者:User

java多態講解,java多態

JAVA多態

一、相關的類結構

class A ...{  //create by danielinbiti         public String show(D obj)...{                  return ("A and D");           }            public String show(A obj)...{                  return ("A and A");           }   }   class B extends A...{           public String show(B obj)...{                  return ("B and B");           }           public String show(A obj)...{                  return ("B and A");           }   }  class C extends B...{}  class D extends B...{}

二、測試回合

        A a1 = new A();          A a2 = new B();          B b = new B();          C c = new C();           D d = new D();           System.out.println(a1.show(b));   ①          System.out.println(a1.show(c));   ②          System.out.println(a1.show(d));   ③          System.out.println(a2.show(b));   ④          System.out.println(a2.show(c));   ⑤          System.out.println(a2.show(d));   ⑥          System.out.println(b.show(b));    ⑦          System.out.println(b.show(c));    ⑧          System.out.println(b.show(d));    ⑨
三、運行結果

①   A and A②   A and A③   A and D④   B and A⑤   B and A⑥   A and D⑦   B and B⑧   B and B⑨   A and D

四、總結

以A a2=new B()為例。

1、a2隻能訪問A的資訊(指的是編譯期編譯器只知道a2是A類型,不知道a2具體子類對象,只有運行期才知道指向什麼對象),而子類重寫的方法,父類中也存在,即B重寫的方法,A裡也有(如果B裡有但是A裡沒有的方法,a2也不能直接調用),所以a2可以訪問,但是調用的時候(注意這裡指的是運行期),a2實際指向的是B對象,所以調用的是B對象的同名同型別參數方法。所以a2.show(b)調用的是show(A obj),因為A引用不到show(B obj)。

註:編譯期是編譯器檢查文法和類型,運行期是解析器解析虛擬碼為機器指令而執行,編譯期編譯器會檢查a2的存取範圍,也就是a2的訪問不超過A的資訊就不會出錯,運行期解析器會解析方法的代碼指令。

聯繫我們

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