2016-03-30 69 views
2

的,我有以下接口:接口方法採取相同的實現接口

public interface ClusterPopulation 
{ 
    public double computeDistance(ClusterPopulation other); 
} 

是否有可能接口本身內指定,ClusterPopulation的是實現一個只能拿一個實現作爲computeDistance的說法?

唯一approching的解決方案,我看到的是下面的,但我不喜歡它:

泛型接口重新定義:

public interface ClusterPopulation 
{ 
    public <T extends ClusterPopulation> double computeDistance(T other); 
} 

內執行,拋出IllegalArgumentException如果從參數不好的類型,如果類型沒問題的話可以做一些演員...... Meeeeh!

即使使用這種方法,最終用戶只知道約束的閱讀文檔/查看代碼執行/試錯...

任何更好的解決方案?

+0

http://stackoverflow.com/questions/7354740/is-there-a-way-to-refer-to-the-current-type-with-a-type-variable – biziclop

回答

5

您有使用泛型的正確思路,但不是將其應用於該方法,而是將其應用於整個界面。

public interface ClusterPopulation<T extends ClusterPopulation<T>> 
{ 
    double computeDistance(T other); 
} 

這允許實現自己定義T

public class ClusterPopulationA implements ClusterPopulation<ClusterPopulationA> { // ... 

但是,它並不允許實現將其定義爲別的東西。

public class BreaksPattern implements ClusterPopulation<ClusterPopulationA> 

包括你的文檔,所有子類應該定義的類型參數T作爲自己的類英寸

0

在我看來,你的設計存在一個缺陷導致問題。從你提供的內容來看,ClusterPopulation似乎應該是一個類,而不是一個接口。讓我們看看這種方法,

public double computeDistance(ClusterPopulation other); 

這是什麼意思?這意味着一個類型爲ClusterPopulation的對象被傳遞給這個方法。此外,這個對象必須有一些屬性,否則如果它不是這個對象,那麼你將如何計算距離這個對象的距離?結合這兩個觀察,可以得出結論,ClusterPopulation應該是一個類,以便擁有該類型的對象。當我講一堂課時,它可以是具體的或抽象的。讓我們來看看抽象類的情況。現在

public abstract class ClusterPopulation 
{ 
    // common attributes, if any 

    abstract public double computeDistance(); 
} 

public class A extends ClusterPopulation { 

    public double computeDistance() { 
     // do some computation based on ClusterPopulation attributes 

    } 

} 

public class B extends ClusterPopulation { 

    public double computeDistance() { 
     // do computation based on ClusterPopulation attributes 

    } 

} 

,你會使用這種方式:

ClusterPopulation a = new A(); 
ClusterPopulation b = new B(); 

double aResult = a.computeDistance(); 
double bResult = b.computeDistance(); 

請注意,您需要限制在這裏執行。雖然ab是ClusterPopulation類型的對象,但computeDistance()僅適用於調用對象的具體類型。

相關問題