java 继承多态的一些理解和不理解

1.向上转型的一个误区

一直以为Child 继承Parent以后, Parent p = new Child();  p可以调用Child类中拓展Parent的方法,原来必须在强制转换成Child类才可以。代码如下:

class Parent{
    public void f(){};
    public void g(){};
}
class Child extends Parent{
    public void f(){};
    public void g(){};
    public void h(){};
    public void i(){};
}
public class ParentSub {
    public static void main(String[] args){
        Parent  [] p = {new Child(),new Parent()};
        p[0].f();
     //p[1].h(); error p[
1].g(); //((Child)p[1]).h(); error ((Child)p[0]).h(); } }

  

  从 p[1].h(); 无法使用我感受到了糊涂,如果Child 拓展了Parent 的方法,那是不是意味着在多态中不能动态的用到拓展的功能呢?

     那么从下面的这个向上转型(子类被转化为父类),可是又缺少了子类的拓展方法。

 1 package com.ebay.polymorphic;
 2 
 3 class Parent2{
 4     public void f(){};
 5     public void g(){};
 6 }
 7 class Child2 extends Parent2{
 8     public void f(){};
 9     public void g(){};
10     public void h(){};
11     public void i(){};
12 }
13 public class ParentSub2 {
14     public void polymorphic(Parent2 p)
15     {
16         p.f();
17         p.g();
18         //p.h(); 错误,可是如果我想用到Child类的拓展方法 h 和i 怎么办呢,难道必须重新写一个方法polymorphic(Child p)?
19     }
20     public static void main(String[] args){
21         ParentSub2 ps = new ParentSub2();
22         Parent2 p = new Child2();
23         ps.polymorphic(p); 
24     
25     }
26 }

  我想如果在编程过程中Parent方法设计不合理,我想在 polymorphic(Parent2 p) 中调用 子类的方法的话,是不是必须重写一个方法不能利用多态的效果呢?这样多态的效果不是消失了吗?我的理解:是不是只有Child在要使用多态的方法(polymorphic)里完全的使用Parent类的已有方法才行,如果想要使用Child的拓展方法,就不能想在多态的方法里实现,必须重写。     有请其他人士来解决,我下次想到了继续来更新。

每天进步一点点。
原文地址:https://www.cnblogs.com/liushuiwuqing/p/3305308.html