2016-03-30 71 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()仅适用于调用对象的具体类型。

相关问题