我有以下界面:
public interface ClusterPopulation
{
public double computeDistance(ClusterPopulation other);
}
是否可以在接口(interface)本身中指定 ClusterPopulation 的实现 A 只能将 A 实现作为computeDistance 的参数?
我看到的唯一接近的解决方案如下,但我不喜欢它:
使用泛型重新定义接口(interface):
public interface ClusterPopulation
{
public <T extends ClusterPopulation> double computeDistance(T other);
}
在实现中,如果参数不是来自好的类型,则抛出 IllegalArgumentException,如果类型正确,则进行一些强制转换... Meeeeh!
即使采用这种方法,最终用户也只能通过阅读文档/查看代码实现/试验和错误来意识到限制...
还有更好的解决方案吗?
最佳答案
您对使用泛型的想法是正确的,但不要将其应用于方法,而是将其应用于整个接口(interface)。
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
定义为其自己的类。
关于java - 接口(interface)方法采用相同的接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319105/