2014-02-07 42 views
0

美好的一天開發者。是否有可能實現接口並在該接口後執行邏輯

所以存在的問題是:

我需要MyClass類方法doSomething();實現接口IMyInterface和覆蓋方法doSomethiing()其他類我們叫他TheOtherClass還實現IMyInterface和替代方法doSomethiing()和加實現的一些邏輯這doSomething()方法(在TheOtherClass)。

問:

  • 我怎樣才能使MyClass觸發doSomething()實施doSomething()方法從TheOtherClass automaticaly
  • 另外,如果MyClass調用我想doSomethig()方法automaticaly調用?
+0

您可以從常見的[class]實現中派生出來,或者提取「something」並使用封裝。 – user2864740

+0

我認爲'TheOtherClass'和'MyClass'的構造函數是*自動觸發器的解決方案* ... –

回答

1

我覺得這樣。

public class TheOtherClass implements IMyInterface{ 
    public void doSomething(){} 
} 

public class MyClass implements IMyInterface{ 

// Instance initialization block: 
// Runs before the constructor each time you instantiate an object 
{ 
    this.doSomething() 
} 

    public MyClass(){ 
    } 

    IMyInterface theOtherClass = new TheOtherClass(); 

    public void doSomething(){ 
    theOtherClass .doSomething(); 
    //Add more logic here 
    } 
} 

而是在構造函數調用DoSomething的的按本線程link我建議用實例初始化塊讀更多here

+0

無論如何這是硬編碼。我寧願將公共類MyClass實現IMyInterface添加到MyClass,並只覆蓋doSomethig()這是它。可能嗎?我知道我使用Spring和ypu實現Interface和方法,它們會自動觸發。也是我的願望 – user3013553

+0

你從來沒有說過有關Spring XD的東西,它改變了上下文 – Koitoer

+0

我建議然後在調用某些方法或構造函數的情況下使用AOP來調用操作。請更新您的問題或打開一個新的,爲此選擇一個正確的。 – Koitoer

0

你可以試試這個

1. make MyClass sub-class of TheOtherClass 
2. call to super.doSumething() in MyClass's doSomething() method. 

這將成爲雙方的目的。 和b'coz它會重寫你可以改變方法的邏輯。 以獲取詳細信息click here