简述每一个输出的原因
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(Object 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 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();
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的对象,名字为a1,a1对象调用show方法,传递的参数为b,但show方法中的参数没有B类型的,所以就会向上转型,B继承了A,所以转型为A,show方法中有参数是A类型的,所以输出结果为A and A
2:同理,show方法里也没有接收C类型的参数,所以也需要向上转型,
C->B->A,输出结果也是A and A
3:D继承了B,B继承了A,show方法中有接收类型为D的参数,所以输出结果为A and D
4:A类型的a2创建了一个B类型的对象,A,B在堆中都会开辟内存,B类中重写的show方法,所以B类型的对象这三个方法都可以调用
而A类型的对象只可以调用绿色的两个方法
所以当a2调用show方法传参为B类型的数据时,调用的方法为
show(A boj){syso("B and A")}
输出结果为B and A
5:同理C继承了B,所以会向上转型C->B->A直到show方法中有可以接收这个类型的参数为止,所以输出结果为B and A
6:D继承B,B继承A,方法中本身就有接受D类型的参数,所以输出结果为
A and D
7:创建了一个B类型的对象,B继承A 重写了A中的show方法,所以调用show方法,向上转型,输出结果为B and A
8:同理,输出结果为B and A
9:调用接收数据类型位D的方法,输出结果为A and D