转载于:https://blog.csdn.net/weixin_35638540/article/details/54730164
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 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
前面三个输出估计没有问题,接下来说明一下第四个,首先a2是A类的引用变量,它所指向的对象是B类的对象,可以看出这就是多态的特性,a2.show(b);计算机的执行过程为:首先到父类中寻找show(B obj)这个方法,但是发现找不到,于是找到形参为A定义的show(A obj)这个函数,把b赋值给a,在这一步上又有出现多态的特性,此时按理来说是输出的“A and A”,但是不然,因为show(A obj)这个函数被子类B重写了所以说要调用子类中的show(A obj)这个函数,以上三步是执行全过程,由此可以看出,多态特性中用父类变量调用成员方法是通过子类对象来调用的,所以最后一步调用了子类重写父类的成员方法。有些书上总结了一些公式,但我觉得这种问题还是要从解析内存上理解,后面的几个也差不多。