我有以下界面:
public interface ClusterPopulation
{
public double computeDistance(ClusterPopulation other);
}是否可以在接口本身中指定ClusterPopulation的实现A只能作为computeDistance的参数?
我看到的唯一批准解决方案如下,但我不喜欢它:
重新定义具有泛型的接口:
public interface ClusterPopulation
{
public <T extends ClusterPopulation> double computeDistance(T other);
}在实现中,如果参数不是来自好类型,则抛出IllegalArgumentException,如果类型确定,则执行一些强制转换.Meeeeh!
即使采用这种方法,最终用户也只能通过阅读文档/查看代码实现/试用和错误来了解约束.
有更好的解决办法吗?
发布于 2016-03-30 20:34:56
您对使用泛型有了正确的想法,但是与其将其应用于方法,不如将其应用于整个接口。
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定义为自己的类。
发布于 2016-03-31 17:50:58
在我看来,您的设计中有一个缺陷会导致问题。从您所提供的情况来看,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();请注意,您需要的限制在这里强制执行。尽管a和b都是ClusterPopulation类型的对象,但computeDistance()仅适用于调用对象的具体类型。
https://stackoverflow.com/questions/36319105
复制相似问题