java 繼承多型的一些理解和不理解

流水無情88發表於2013-09-06

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的擴充方法,就不能想在多型的方法裡實現,必須重寫。     有請其他人士來解決,我下次想到了繼續來更新。

 

 

相關文章