我的接口层次结构类似于-
interface Type
{
Type copy();
};
interface SubType extends Type
{
};
interface SubSubType extends SubType
{
};
还有一个具体的 class
public class Concrete implements SubSubType
{
@Override public Concrete copy() { return new Concrete(); }
}
我希望能够在Type上调用copy()并获得Type,在SubType上调用copy()并获得SubType,等等。这可以实现吗?可能是泛型?
提前致谢。
最佳答案
像这样:
public interface Type {
public Type copy();
}
public interface SubType extends Type {
public SubType copy();
}
public class Concrete implements Type {
@Override
public Concrete copy() {
return new Concrete();
}
}
public class SubConcrete implements SubType {
@Override
public SubConcrete copy() {
return new SubConcrete();
}
}
public static void main(String[] args) {
Type type = new Concrete();
SubType subType = new SubConcrete();
Type newType = type.copy();
SubType newSubType = subType.copy();
}