我有一个界面HTTPSequence
。我还有一个抽象类AbstractHTTPFactory
,后者又有一个返回ArrayList<HTTPSequence>
的抽象方法。在从AbstractHTTPFactory
派生的类中,我想覆盖这些方法以返回ArrayList<[Class implementing HTTPSequence]>
。
有可能吗?现在编译器给出了一个错误,表明我将覆盖方法签名更改为HTTPSequence
。
// abstract class with abstract method returning ArrayList of objects implementing interface
abstract public class AbstractHTTPFactory {
abstract ArrayList<HTTPSequence> make();
}
// Specific class that returns ArrayList of objects of the class implementing HTTPSequence
public class RecipesHTTPFactory extends AbstractHTTPFactory{
public ArrayList<Recipe> make() {
}
}
// interface
public interface HTTPSequence {
}
// one of the classes implementing the above interface
public class Recipe implements HTTPSequence {
}
Eclipse给我的信息是:
此行有多个标记 - 返回类型与AbstractHTTPFactory.make()不兼容 - implements .... ider.AbstractHTTPFactory.make
答案 0 :(得分:6)
您可以编写AbstractClass方法来返回ArrayList<? extends Interface>
,然后您不必更改派生类方法签名
答案 1 :(得分:0)
以下设计允许您避免必须返回limited use to the caller的通配符泛型类型:
abstract public class AbstractHTTPFactory<T extends HTTPSequence> {
abstract ArrayList<T> make();
}
public class RecipesHTTPFactory extends AbstractHTTPFactory<Recipe> {
public ArrayList<Recipe> make() { ... }
}
现在,您可以致电new RecipesHTTPFactory().make()
并取回ArrayList<Recipe>
而不是ArrayList<? extends HTTPSequence>
。
另请注意,除非来电者明确要求ArrayList
,make()
List<T>
才能返回{{1}}。