这篇文章是我看了这个参考博客的解题分析过程,查看下面结果前请将它看懂,有需要再与我讨论。
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 Demo {
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)
1、a1.show(b)
- a1是类型为A的引用对象,实际指向对象也为A。
a1.show(b) == this.show(b) == A.show(b)
。然后在A类中没有找到show(b)
方法,于是进入下一个调用级别super.show(O)
,- 此题中A的父类只有
Object
,它也没有show(b)
方法,于是进入this.show((super)O)
级别。 - 此时为
this.show((A) b) ==this.show(a)
,this指A,调用A中方法show(a)
得到结果: “A and A”。
2、a1.show(c)
- a1是类型为A的引用对象,实际指向对象也为A。
a1.show(c) == this.show(c) == A.show(c)
。然后在A类中没有找到show(c)
方法,于是进入下一个调用级别super.show(O)
,- 此题中A的父类只有
Object
,它也没有show(c)
方法,于是进入this.show((super)O)
级别。 - 此时为
this.show((A) c) ==this.show(a)
,this指A,调用此方法得到 “A and A”。
3、a1.show(d)
- a1是类型为A的引用对象,实际指向对象也为A。
a1.show(d) == this.show(d) == A.show(d)
。然后在A类中找到show(c)
方法,于是结果为:“A and D”。
4、a2.show(b)
- 首先,a2是类型为A的引用对象,实际指向类型为B,涉及向上转型。它俩共同确定可调用的方法只有A中的
show(D obj) 跟 show(A obj)
。 a2.show(b)==this.show(b)
,这里的this指向B。在B中找到了show(b)
方法,但是不能调用,只能调用它俩共同确定的方法。故转向下一个级别super.show(O)
,super指向A- 在A中找
show(b)
方法,没有找到,于是进入this.show((super)O)
, this 指向B。 - 在B中找
this.show((A) b0==this.show(a)
方法,找到了,调用该方法。输出“B and A”。
5、a2.show(c)
- 首先,a2是类型为A的引用对象,实际指向类型为B,涉及向上转型。它俩共同确定可调用的方法只有A中的
show(D obj) 跟 show(A obj)
。 a2.show(c)==this.show(c)
,这里的this指向B。在B没找到show(c)
方法。故转向下一个级别super.show(O)
,super指向Asuper.show(c)==a.show(c)
,A中没有此方法,故又转到this.show((super)O)
级别。this.show((super)O)==this.show((A) c)==this.show(a)
,这里this指B,B有此方法,故输出结果为:“B and A”。
6、a2.show(d)
- 首先,a2是类型为A的引用对象,实际指向类型为B,涉及向上转型。它俩共同确定可调用的方法只有A中的
show(D obj) 跟 show(A obj)
。 a2.show(d)==this.show(d)
,这里的this指向B。在B没找到show(d)
方法,就算找到了也不能调用。故转向下一个级别super.show(O)
,super指向Asuper.show(d)==a.show(d)
,A中有此方法,故输出结果为:“A and D”。
7、b.show(b)
- b编译时类型与运行时类型均为B,不涉及转型
- 在B中找到
show(b)
方法,直接输出结果:“B and B”
8、b.show(c)
- b编译时类型与运行时类型均为B,不涉及转型
- B中没有
show(c)
方法,进入下个级别super.show(O)==A.show(c)
,A中也没有show(c)
方法,又进入下一个级别this.show((super)O)
this.show((super)O) == B.show((B) c) == b.show(b)
,B中有show(b)
方法,输出结果:“B and B”。
9、b.show(d)
- b编译时类型与运行时类型均为B,不涉及转型
- B继承A,故B中有方法
show(d)
,直接调用该方法输出结果:“A and D”。