2011-06-07 61 views
5

我有3類A,B和C,這些延伸另一類D.如何同樣的方法添加到多個類(活性)

d類具有在所有的類A,B中使用的方法,和C.現在

問題是類A,B和C應擴展不同類別和類只使用同樣的方法D.

我無法相信,我應該複製和粘貼的方法在我所有的課堂上。有沒有像C中包含函數的東西?

順便說一下,我正在開發一個Android應用程序。 D類擴展了Activity,並有一個管理Android活動A,B和C的通用菜單的方法(這是Android文檔中報告的官方方法)。不過,我需要這些活動擴展不同的類,如ActivityList,而不僅僅是Activity類。

回答

6

如果你的方法並不需要從訪問私有狀態,d類中添加一個靜態方法,並調用靜態方法A,B,C

如果你的方法確實需要訪問私有狀態,看你是否能分解出需要通過添加一個包私人吸氣每個班使用私有狀態,然後使用方法A.

否則,試圖分解出一些邏輯來共同接口而不是超類。

否則,請嘗試委託給助手類。 (例如組合物而不是繼承作爲@Marcelo指示)

否則,重複的方法中的每個類A,B,C.


作爲共同接口方法的一個例子,具有靜態方法組合在D中:

interface MyThing 
{ 
    public void doMyThing(String subject); 
    public List<String> getThingNames(); 
} 

class D 
{ 
    static void doSomethingComplicatedWithMyThing(MyThing thing) 
    { 
     for (String name : thing.getThingNames()) 
     { 
     boolean useThing = /* complicated logic */ 
     if (useThing) 
      thing.doMyThing(name); 
     } 
    } 
} 

class A extends SomeClass implements MyThing 
{ 
    /* implement methods of MyThing */ 

    void doSomethingComplicated() 
    { 
     D.doSomethingComplicatedWithMyThing(this); 
    } 
} 

class B extends SomeOtherClass implements MyThing 
{ 
    /* implement methods of MyThing */ 

    void doSomethingComplicated() 
    { 
     D.doSomethingComplicatedWithMyThing(this); 
    } 
} 

class C extends YetAnotherClass implements MyThing 
{ 
    /* implement methods of MyThing */ 

    void doSomethingComplicated() 
    { 
     D.doSomethingComplicatedWithMyThing(this); 
    } 
} 
3

您應該在每個A,B和C類定義中都有一個D類型的實例變量,並使用該實例中的方法。這樣A,B和C仍然可以擴展其他類。

在這種情況下,您贊成composition高於inheritance

1

Java不支持多繼承..一個類只能擴展一個類。 也許使用接口是一個好主意。你可以創建一個包含D類方法的接口,並使類A,B和C來實現這個接口..我不知道這是否有幫助。以下是可能對您有用的鏈接:http://java.sys-con.com/node/37748

相關問題