假设我有这个接口(interface)(没有参数化)
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)的子类:
interface MyInterface<T extends MyInterface<T>> {
T copy();
}
class Foo implements MyInterface<Foo> {
public Foo copy() {
return null;
}
}
关于java - java接口(interface)中的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24069246/