日期:2014-05-20  浏览次数:20755 次

【送分】一个多态的例子需要讲解
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...{} 


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)); ⑨



答案

  ① 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



第一个 System.out.println(a1.show(b)); ①答案为什么是 A and A 这个我都没搞懂 为什么不是别的?剩下的谁能帮解答一下?  
送分!

------解决方案--------------------
a1是A的实例,调用A的show方法,根据参数,b是B的实例,因为B是A的子类,也就是"B是A",所有调用show(A obj),就打印了A and A了
------解决方案--------------------
接分,好好看看书
------解决方案--------------------
System.out.println(a1.show(b)); ① a1 是A的对象 ,b是B的对象,而B的直接父类是A所以走 show(A obj) ;
System.out.println(a1.show(c)); ②a1 是A的对象 ,c是C的对象,C-->B-->A,所以C可以转为A所以也是show(A obj)
System.out.println(a1.show(d)); ③d是D的对象,所以就直接走show(D obj)了

------解决方案--------------------
System.out.println(a2.show(b)); ④ a2 是B的对象,所以走的是B.show(A obj)
System.out.println(a2.show(c)); ⑤ a2 是B的对象,所以走的是B.show(A obj)
System.out.println(a2.show(d)); ⑥a2 是B的对象,由于继承关系,B中也是存在 B.show(D obj),只不过和A中时一样的
System.out.println(b.show(b)); ⑦.//自己分析
System.out.println(b.show(c)); ⑧//自己分析
System.out.println(b.show(d)); ⑨//自己分析
------解决方案--------------------
System.out.println(a1.show(b)); ①
System.out.println(a1.show(c)); ②
B,C,D都是A类的子类,a1指向A的对象,b指向B的对象,c指向的对象,①中,A是B的父类,所以调用A中的show(A obj)方法,,②同理,return ("A and A")

System.out.println(a1.show(d)); ③
直接将D的对象d传给show(D obj),return ("A and D")

System.out.println(a2.show(b)); ④
System.out.println(a2.show(c)); ⑤
a2指向B类的对象,多态,故调用B类方法,b和c都是A类的子对象,所以当成A类的参数,调用show(A obj),return ("B and A")

System.out.println(a2.show(d)); ⑥
B类继承了A类的show(D obj)方法,故调用此方法,return ("A and D")

System.out.println(b.show(b)); ⑦
B类对象调用B类方法,show(B obj),return ("B and B")

System.out.println(b.show(c)); ⑧
c是B类的子对象,当成B类参数传进去,show(B obj),return ("B and B")

System.out.println(b.show(d)); ⑨
B类继承了A类的show(D obj)方法,故调用此方法,return ("A and D")