方法的匹配顺序

匹配顺序: this.show(O), super.show(O),
this.show(super(O)), super.show(super(O))
1)先确保参数完全匹配O的前提下,依次匹配this与super。
2)再考虑参数用super(O)渐近匹配O,依次匹配this与super
3)当存在子类覆盖父类方法时,根据new子类实例的原则,先调子类方法。

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 class TestDT{
  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(a2.show(b)); //  ④  B and A
        System.out.println(a2.show(c)); //  ⑤  B and A
        System.out.println(a2.show(d)); //  ⑥  A and D
        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
  }
}

猜你喜欢

转载自blog.csdn.net/qq_38431927/article/details/77851629