多态详解(1)

来源:互联网 发布:广发华福软件 编辑:程序博客网 时间:2024/04/30 10:13

看到过的一些东西,自己总结如下:如有错误之处,请指出!

  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. class C extends B...{}  
  17. 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

    要理解这些问题:一定要记得:当超类对象引用变量引用子类对象时,被引用对象的类型而不是引用变量的类型决定了调用谁的成员方法,但是这个被调用的方法必须是在超类中定义过的,也就是说被子类覆盖的方法。

    也就是说必须满足:

    1.存在方法覆盖(字段不会覆盖,子类会保存父类字段的拷贝,可以参考:多态详解(2))

    2.父类引用指向子类对象

    3.最终调用哪个方法是由你new出来的对象决定的,即调用你new出来的对象中覆盖的父类的方法

     

    比如a2.show(b),传递进来的是B的对象,为什么不返回B and B呢?因为没有覆盖,A类中并没有这个方法,这是子类的方法,然后就会查找父类即A类中有没有对象B做参数的方法,还没有,就在B中查找参数为A父类的方法,所以返回为B and A

    即查找顺序为:this.show(Type  param)、super.show(Type  param)、this.show((superType)  param)、super.show((superType  )param)。

    再比如第9个,B类没有,在A类中找到了,所以打出A and D

     

    以上只是个人对文章的理解,表达可能不清楚,可以参看http://developer.51cto.com/art/200906/130414.htm