向上转型与向下转型

来源:互联网 发布:mysql union 用法 编辑:程序博客网 时间:2024/06/05 17:17
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引用A对象,因为B继承A,所以参数传B相当于传A②   A and A    同上③   A and D    A中有入参是D的方法,所以是直接调用,如果去掉这个方法,还是会满足A and A④   B and A    A a2 = new B()是向上转型,此时引用是父类,其没有子类的个性化方法,所以传B对象进来时,不会找子类的方法,而是找到父类的方法,如果是向下转型
                如B b1=(B)a2;此时就可以调用个性化的B,此时答案就为B and B⑤   B and A    同上⑥   A and D    同③⑦   B and B    子类调用,所以可以调到子类直接的方法里面⑧   B and B    C的父类是B,所以同上⑨   A and D    子类没有找到传D的方法,就往父类上面找