特别是a2.show( )输出的结果不理解。求大神指点第一次提问
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{}
class D extends B{}
public class Test1{
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));
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));
System.out.println(b.show(b));
System.out.println(b.show(c));
System.out.println(b.show(d));
}
}
a2.show(b): b and a
a2.show(c): b and a
a2.show(d): a and d
首先看着内存的布局图理解,首先a2的实在是一个对象B,但是由于a2是当作A来new的,所以a2指向的只是B中的A,它看不到B的方法的,
对于传入一个b来说,b是B的一个实例,我们看A中show方法的参数没有是B的,由于B是一个A,所以找父类,当成一个A传进去,注意,我们new的时候,new出来的实质是个B,B对A中的方法show(A)方法进行了重写(此时B有三个方法),所以直接调用B的show(A)方法,打印出“b and a",
第二第三个类似,只有内存布局画出来了,就好理解了!比如第二个c也是当成A传进去的(c是一个A),d直接传进去,A中有方法对应,只要第一个理解了,其他都是一样的!