Java多态性
1 class A ...{ 2 public String show(D obj)...{ 3 return ("A and D"); 4 } 5 public String show(A obj)...{ 6 return ("A and A"); 7 } 8 } 9 class B extends A...{ 10 public String show(B obj)...{ 11 return ("B and B"); 12 } 13 public String show(A obj)...{ 14 return ("B and A"); 15 } 16 } 17 class C extends B...{} 18 class D extends B...{}
下面程序运行结果:
1 A a1 = new A(); 2 A a2 = new B(); 3 B b = new B(); 4 C c = new C(); 5 D d = new D(); 6 System.out.println(a1.show(b)); ① 7 System.out.println(a1.show(c)); ② 8 System.out.println(a1.show(d)); ③ 9 System.out.println(a2.show(b)); ④ 10 System.out.println(a2.show(c)); ⑤ 11 System.out.println(a2.show(d)); ⑥ 12 System.out.println(b.show(b)); ⑦ 13 System.out.println(b.show(c)); ⑧ 14 System.out.println(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
关于第四条解释:
解析:
①,②,③调用a1.show()方法,a1 属于A类,A类有两个方法show(D obj)和show(A obj)。①a1.show(b),参数b为A类的子类对象,这里为向上转型,相当于A obj=b;所以调用show(A obj)方法,得到A and A结果。②同理,③参数为d,调用show(D obj),得到A and D。
④,⑤,⑥调用a2.show()方法,A a2 = new B();是向上转型,所以对a2方法的调用,使用A1类的方法show(D obj)和show(A obj),但此时show(A obj)已经被重写为return ("B and A"), ④a2.show(b),调用show(A obj),得到B and A。⑤同理,⑥调用show(D obj),得到A and D。
⑦,⑧,⑨调用b.show()方法,b为B类,B类的show方法有继承的show(D obj),自己的两个show(B obj)、show(A obj)。
⑦调用show(B obj),得到B and B,⑧向上转型,调用show(B obj),得到B and B⑨show(D obj),得到A and D