假设我有一个像这样的界面:
public interface Replicateable<T> {
void replicate(T entity);
}
另一个扩展它
// here Identifiable is just another interface
public interface Entity extends Identifiable, Replicateable<Entity> {
//some declarations here
}
在这条链的末端,我想要类似的东西
public class ConcreteEntity implements Entity {
@Override
public void replicate(ConcreteEntity entity) {
// here goes some logic turning current entity
// to a replica of a passed one
}
}
除了使 Entity
接口(interface)通用之外,还有什么方法可以实现吗?我宁愿避免这种情况。
所以我试着
1. 保持原样,这不起作用,因为 replicate()
实现需要一个 Entity
参数,而不是具体参数
2.为实体类添加Replicateable
权限
public class ConcreteEntity implements Entity, Replicateable<ConcreteEntity> { ... }
这给了我'Replicateable' cannot be inherited with different type arguments: 'Entity' and 'ConcreteEntity'
(为什么它不起作用似乎是可以理解的)。
3. 覆盖Entity
接口(interface)中的replicate()
(也没有结果,甚至不确定它是否有意义)。
4. 制作一个replicate()
泛型而不是Replicateable
本身(不确定如何正确)
如有任何正确的建议,我们将不胜感激。
最佳答案
Entity
必须是通用的,编译器才能知道哪种类型可以传递给 replicate
:
Entity<ConcreteEntity> e = ...;
e.replicate(...); // <-- aha. Can only pass a ConcreteEntity (or a subtype of)
使用多态性可能更有意义:
interface Replicateable<T> {
T replicate();
}
interface Entity extends Identifiable, Replicateable<Entity> {
// Entity replicate();
}
可以使用复制构造函数实现:
class ConcreteEntity implements Entity {
public ConcreteEntity(ConcreteEntity other) {...}
@Override
public ConcreteEntity replicate() { // <-- uses return type overriding
return new ConcreteEntity(this);
}
}
Entity e1 = new ConcreteEntity();
Entity copy1 = e1.replicate();
ConcreteEntity e2 = new ConcreteEntity();
ConcreteEntity copy2 = e2.replicate();
关于java - 在实现类中缩小通用 super 接口(interface)的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729511/