java多態例子

來源:互聯網
上載者:User

標籤:

多態存在的三個必要條件
一、要有繼承;
二、要有重寫;
三、父類引用指向子類對象。

代碼部分:

class A {    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 {}

然後開始搞腦子了:

public static void main(String[] args) {        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(a1));        System.out.println(a1.show(a2));        System.out.println(a2.show(a1));        System.out.println(a2.show(a2));        System.out.println(b.show(a1));        System.out.println(b.show(a2));        System.out.println(c.show(a1));        System.out.println(c.show(a2));        System.out.println(d.show(a1));        System.out.println(d.show(a2));        System.out.println("分割線**************************************");        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));        System.out.println(c.show(b));        System.out.println(c.show(c));        System.out.println(c.show(d));    }

運行結果:

A and AA and AB and AB and AB and AB and AB and AB and AB and AB and A分割線**************************************A and AA and AA and DB and AB and AA and DB and BB and BA and DB and BB and BA and D

為了方便理解,我列了下每個類的method table

Ashow(D) -> A.show(D)show(A) -> A.show(A)B,C, Dshow(D) -> A.show(D)show(B) -> B.show(B)show(A) -> B.show(A)

 

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.