Java多態(二)

來源:互聯網
上載者:User

標籤:

public class ExtendsTest {    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(b));     //A and A        System.out.println(a1.show(c));     //A and A        System.out.println(a1.show(d));     //A and D                System.out.println("=======");        System.out.println(a2.getClass().getName());        /**         * A a2 = new B();向上轉型,a2調用show()方法之前先去判斷父類A中是否有該方法         * 若有則調用B中相應的方法,若是帶有參數的方法如a2.show(b),其中b是B類型的,父類         * 中沒有該方法,子類B中有該方法,但由於是向上轉型不會直接調用B類中的方法,而是判斷是否         * 父類中是否有參數b的父類型的同名方法(即A中沒有show(B b)的方法而有show(A a)方         * 法),因此程式最終會調用B類中的show(A obj)方法。         * 因此a2.shw(b)、a2.show(c)結果為B and A;a2.show(d)結果為A and D         */        System.out.println(a2.show(b));     //B and A        System.out.println(a2.show(c));     //B and A        System.out.println(a2.show(d));     //A and D                /**         * B b = new B();B類建立一個普通樣本對象,b.show(b)的結果很明顯就是B and B;         * b.show(c)父類和子類都沒該方法(B中沒有找到,轉而到B的超類A裡面找),因此轉到第三優         * 先級,由於c是b的子類,因此到B類中找到show(B obj),最終結果B and B;         * b.show(d)在B類中沒找到,轉而倒父類中尋找,調用父類的方法,結果A and D;         * 因為A、B中都有方法show(A obj),根據Java多態-方法的重寫,最終調用子類中的方法,結         * 果B and A。         */        System.out.println("=======");        System.out.println(b.show(b));      //B and B        System.out.println(b.show(c));      //B and B        System.out.println(b.show(d));      //A and D        System.out.println(b.show(a1));      //B and A                /**         * 方法調用的優先問題 ,優先順序由高到低依次為:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。         */    }}class A {      public A(){        System.out.println("A構造器被調用");    }    public String show(D obj){             return ("A and D");      }       public String show(A obj){             return ("A and A");      }   }   class B extends A{     public B(){        System.out.println("B構造器被調用");    }    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{}

 

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.