0

我有一个界面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() 不兼容 - 实现 ....ider.AbstractHTTPFactory.make

4

2 回答 2

6

您可以编写您的 AbstractClass 方法以返回ArrayList<? extends Interface>,然后您不必更改派生类方法签名

于 2012-04-12T11:02:05.187 回答
0

以下设计将允许您避免返回通配符泛型类型,这对调用者的使用有限

abstract public class AbstractHTTPFactory<T extends HTTPSequence> {
    abstract ArrayList<T> make();
}

public class RecipesHTTPFactory extends AbstractHTTPFactory<Recipe> {
    public ArrayList<Recipe> make() { ... }
}

现在您可以调用new RecipesHTTPFactory().make()并取回 anArrayList<Recipe>而不是ArrayList<? extends HTTPSequence>.

另请注意,除非调用者特别期望 a ArrayList否则最好返回make()a List<T>

于 2012-04-12T13:11:03.343 回答