对一个多态例题学习的一些思考

来源:互联网 发布:idc 手机出货量数据 编辑:程序博客网 时间:2024/06/05 07:06

一道java多态例题分析

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...{} 
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.

a.类A实例化A,为a1,a1.show(b),编译器会先在A里找B,这时发现没有B

b.则先查看A是否有父类,有父类则查看是否执行父类中符合的方法,若无则下一步

c.将B向上转成A对象,故实际执行了A.class中的show(A  obj)

2.同理,将C向上转为B,找不见,又转为A对象,故实际执行的也是A.class中的show(A  obj)


3.
执行A.class中的show(D obj)

4.

a.父类A引用子类B,这时a2.show(b)会先去A中找对应方法,若无则下一步

b.将B向上转为A,编译器找见对应方法,准备执行

c.又发现实例化子类B将方法重写,故执行B中重写的方法,即B.class中的show(B obj)

5.同上

6.先去A里找见方法show(D obj)并执行了

7.直接执行B.class中的show(B obj)

8.

a.编译器在B中没找见相应方法,则先去父类中查找有无,若无则下一步

b.返回子类并将参数向上转为B,并执行了B.class中的show(B obj)

9.B中无,则找父,父有并执行

警告:

以上内容仅为一个菜鸟对自己学习的总结,有理解不合适的地方欢迎各位前辈及时指出,谢谢

1 0