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(); //調用的順序是 //this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O) //輸出:A and A //先找A中的show沒有show(b)的方法,再找super.show(b),A沒有父類, //再繼續找this.show((super)b),由於b繼承了A,這裡就找到了所以這裡調用了A的show(A)方法 System.out.println(a1.show(b)); //輸出:A and A //同樣,先找A中的show沒有show(c)的方法,再找super.show(c),A沒有父類, //再繼續找this.show((super)c),由於c繼承了B,而B繼承了A,所以這裡還是調用了a的show(a) System.out.println(a1.show(c)); //輸出:A and D //同樣,先找A中的show沒有show(d)的方法,再找super.show(d)這裡就已經找到了 System.out.println(a1.show(d)); //輸出:B and A //先找A中的show沒有show(b)的方法,再找super.show(b),A沒有父類, //再繼續找this(a2).show((super)b),由於b繼承了A,這裡就找到了所以這裡調用了A的show(A)方法 //a2.show(b),a2是一個引用變數,類型為A,則this為a2,b是B的一個執行個體,於是它到類A裡面找show(B obj)方法, //沒有找到,於是到A的super(超類)找,而A沒有超類,因此轉到第三優先順序this.show((super)O), //this仍然是a2,這裡O為B,(super)O即(super)B即A,因此它到類A裡面找show(A obj)的方法, //類A有這個方法,但是由於a2引用的是類B的一個對象,B覆蓋了A的show(A obj)方法,因此最終鎖定到類B的show(A obj),輸出為"B and A”。 System.out.println(a2.show(b)); //輸出:B and A System.out.println(a2.show(c)); //輸出:A and D System.out.println(a2.show(d)); //輸出:B and B System.out.println(b.show(b)); //輸出:B and B //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”。 System.out.println(b.show(c)); //輸出:A and D System.out.println(b.show(d));}}class A {public A(){System.out.println("new A");}public String show(D obj) {//System.out.println("A:"+this.getClass().getName());return ("A and D");}public String show(A obj) {//System.out.println("A1:"+this.getClass().getName());return ("A and A");}}class B extends A {public B(){System.out.println("new B");}public String show(B obj) {//System.out.println("B:"+this.getClass().getName());return ("B and B");}public String show(A obj) {//System.out.println("B1:"+this.getClass().getName());return ("B and A");}}class C extends B {public C(){super();//System.out.println("C:"+super.getClass().getName());}}class D extends B {}