public class Test1{
public static void main(String arg[]){
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));
System.out.println(a1.show(c));
System.out.println(a1.show(d));
System.out.println(a2.show(b));
System.out.println(a2.show(c));
System.out.println(a2.show(d)); //A-D
System.out.println(b.show(b));
System.out.println(b.show(c));
System.out.println(b.show(d));
}
}
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(A obj){
return ("B and A");
}
public String show(B obj){
return ("B and B");
}
}
class C extends B{
public String show(C obj){
return ("C and C");
}
public String show(B obj){
return ("B and C");
}
}
class D extends B{
public String show(D obj){
return ("D and D");
}
public String show(B obj){
return ("B and D");
}
}
A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D
为什么第4个输出不是B and B而是 B and A明明入参就是B类
如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。
类A中的方法show(A obj)
跟类B中的方法show(B obj)
因为参数不同(虽然是有继承关系,但也必须是相同才行),
所以类B中的这个方法并不是对类A中方法的重写,它们之间并没有关系。A a2 = new B();
这样定义的a2对象,只有show(D obj)
和show(A obj)
方法,并且类B中的show(A obj)
方法对A中的show(A obj)
方法重写了,我们在调用的时候,就会走类B中的show(A obj)
方法,所以输出是B and A
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。