classA ...{ publicString show(D obj)...{ return("A and D"); } publicString show(A obj)...{ return("A and A"); } } classB extendsA...{ publicString show(B obj)...{ return("B and B"); } publicString show(A obj)...{ return("B and A"); } } classC extendsB...{} classD extendsB...{}
(二)问题:以下输出结果是什么?
A a1 =newA(); A a2 =newB(); B b =newB(); C c =newC(); D d =newD(); 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));
⑨
(三)答案
① A and
A
② A and A
③ A and D ④
B and A
⑤ B and A
⑥ A and D
⑦ B and B
⑧ B and B
⑨ A and D
(四)分析
①②③比较好理解,一般不会出错。④⑤就有点糊涂了,为什么输出的不是"B
and B”呢?!!先来回顾一下多态性。