2016-04-14 112 views
0

假設我有一個擴展類父類的子類。 Child類有兩個嵌套類nested1和nested2。我想要一個抽象函數在Parent中用參數定義爲nested1並且返回類型爲嵌套2.現在,爲了達到這個目的,我創建了一個函數,它的參數和返回類型都是Object。使用嵌套對象處理父類和子類的繼承

所以,現在,當我實現子類時,我總是需要將對象轉換爲nested1和nested2。我覺得會有更好的方法來實現這一點。有沒有更好的方法來降低複雜性?

還附上了UML enter image description here

回答

3

從一個輸入點的最好辦法是讓父類中的一個接口,在孩子指定嵌套類。這樣你就不需要將參數投射到func上。這不會降低複雜性,但它確實能讓你的意圖變得更加清晰,並減少/消除了投射的必要(總是一件好事)。

public abstract class Parent { 

    interface Interface1 { 
     //Specifications of methods that all child nested classes must have 
    } 

    interface Interface2 { 
     //Specifications of methods that all child nested classes must have 
    } 

    public abstract Interface2 func(Interface1 obj); 

} 

public class Child extends Parent { 

    private static class Impl1 implements Interface1 { 
     //Implementations of methods in Interface1 as they pertain to Child 
    } 
    private static class Impl2 implements Interface2 { 
     //Implementations of methods in Interface2 as they pertain to Child 
    } 


    @Override 
    public Interface2 func(Interface1 obj) { 
    //Should only have to use methods declared in Interface1 
    //Thus should have no need to cast obj. 

    //Will return an instance of Impl2 
    return null; 
    } 
} 

在更廣泛的範圍內,您應該問自己爲什麼每個孩子都需要自己的一套嵌套類。如果可以將嵌套類定義移動到父類(並使其成爲靜態),並且只需在構造過程中根據需要對子類進行定製,則這將變得更簡單。

+0

謝謝! 。嵌套類的定義在所有孩子中是不同的。所以我無法將它們作爲獨立的靜態類。你能想出一種方法來改進設計嗎? – mc20

+0

鑑於這一點,設計問題是爲什麼你需要父項中的抽象方法?假設我有'Parent p = ...',我不知道它的類型,我可以用正確的參數調用'p.func(...)'嗎?如果不是抽象方法沒有意義的話 – Mshnik