[英]generic in an interface in java
说我有这个界面(未参数化)
public interface MyInterface
{
MyInterface copy();
}
如何确保所有copy
实现都返回实际的子类型(而不是MyInterface
)。
例如。,
public Impl implements MyInterface
{
@Override
public Impl copy() <<<<< The returns type of this needs to be 'Impl'
{
return new Impl();
}
}
但是我不能阻止任何实现来做到这一点:
public Foo implements MyInterface
{
@Override
public MyInterface copy() <<<<< The returns type of this needs to be 'Foo'
{
return new Impl();
}
}
您可以指定通用类型,它是接口的子类:
interface MyInterface<T extends MyInterface<T>> {
T copy();
}
class Foo implements MyInterface<Foo> {
public Foo copy() {
return null;
}
}
说我有这个界面(未参数化)
如果要使其保持非参数化状态,那么没有解决方案可以满足您的两个示例。 而且我不明白为什么要对接口进行编程并且不控制接口的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.