標籤:
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多態(二)