多態經典例子理解

public class A {
    public String show(D obj) {
        return ("A and D");
    }

    public String show(A obj) {
        return ("A and A");
    }

}

public class B extends A{
    public String show(B obj){
        return ("B and B");
    }

    public String show(A obj){
        return ("B and A");
    }
}

public class C extends B{

}

public class D extends B{

}

public class Test {
    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("1--" + a1.show(b));
        System.out.println("2--" + a1.show(c));
        System.out.println("3--" + a1.show(d));
        System.out.println("4--" + a2.show(b));
        System.out.println("5--" + a2.show(c));
        System.out.println("6--" + a2.show(d));
        System.out.println("7--" + b.show(b));
        System.out.println("8--" + b.show(c));
        System.out.println("9--" + b.show(d));      
    }
}

 

 

1--A and A
2--A and A
3--A and D
4--B and A
5--B and A
6--A and D
7--B and B
8--B and B
9--A and D

 

先說優先級,優先級由高到低依次爲:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。this

這樣來理解吧,當存在上相轉型時,首先看子類有沒有重寫超類方法,若是調用類重寫超類方法首先執行子類重寫超類的方法,若是調用的子類沒有重寫超類的方法,直接調用超類的方法來執行,當不存在向上轉型時,若是調用的方法在本類中存在則調用,反之 再好比⑧,b.show(c),b是一個引用變量,類型爲B,則this爲b,c是C的一個實例,因而它到類B找show(C obj)方法,沒有找到,轉而到B的超類A裏面找,A裏面也沒有,所以也轉到第三優先級this.show((super)O),this爲b,O爲C,(super)O即(super)C即B,所以它到B裏面找show(B obj)方法,找到了,因爲b引用的是類B的一個對象,所以直接鎖定到類B的show(B obj),輸出爲"B and B」。code

相關文章
相關標籤/搜索