我们先来看代码和问题
public class Test { public static void main(String[] args) { A a = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println(a.show(b)); System.out.println(a.show(c)); System.out.println(a.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(B obj) { return "B and B"; } public String show(A obj) { return "B and A"; } } class C extends B { } class D extends B { }
请问,为什么输出的是以下内容:
B and A
B and A
A and B
我们先分析下面的代码
public class Test { public static void main(String[] args) { A a = new B(); B b = new B(); System.out.println(a.show(b)); } } 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"; } }
我们知道对象能调用的方法是由编译类型
来决定的,运行方法的内容是由运行类型
来决定的(左编译,右运行)。
System.out.println(a.show(b));
调用了 A 类里面的 show 方法,并且传入了 B 类对象,请问调用了哪个 show 方法?
答案是:B 类继承了 A 类,所以调用了 show(A obj) 方法。
如果这里没懂,去回顾一下继承
这时会输出什么?
答案是:运行方法的内容是由运行类型
来决定,也就是 B,所以 a.show(b)
会输出:B and A
。
我们接着分析
public class Test { public static void main(String[] args) { A a = new B(); C c = new C(); System.out.println(a.show(c)); } } 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 { }
System.out.println(a.show(c));
调用了 A 类里面的 show 方法,并且传入了 C 类对象,请问调用了哪个 show 方法?
答案是:C类继承了 B 类,B 类继承了 A 类,所以调用了 show(A obj) 方法。
这时会输出什么?
答案是:运行方法的内容是由运行类型
来决定,也就是 B,所以 a.show(c)
会输出:B and A
。
我们来看最后一个输出语句
public class Test { public static void main(String[] args) { A a = new B(); D d = new D(); System.out.println(a.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(B obj) { return "B and B"; } public String show(A obj) { return "B and A"; } } class D extends B { }
System.out.println(a.show(d));
调用了 A 类里面的 show 方法,并且传入了 D 类对象,请问调用了哪个 show 方法?
答案是:调用了 show(D obj) 方法。
这时会输出什么?
答案是:运行方法的内容是由运行类型
来决定,也就是 B,可是这次该方法没有被重写
所以 会输出:A and D
。
以上是个人分析,有误请务必在评论留言,感谢~~~。