我试图定义并实现一个抽象的setter,它将对象列表作为参数。以下是这个简单想法的要点:
public abstract class MyClass {
public abstract void setThings(List<?> things);
}
public class Bar extends MyClass {
private List<String> things;
@Override
public void setThings(List<String> things) {
this.things = things;
}
}
那不管用。我得到了Method does not override method from its superclass
和both methods have the same erasure, but neither overrides the other
。我理解与擦除有关的后一个错误,但即便如此,我还是找不出正确的方法来做到这一点。我尝试过其他的方法,比如:
public abstract <T> void setThings(List<T> things);
...as和其他几个人一样。我还找到了其他问题/答案,以便接近解决这一问题,但没有一个问题/答案提供了坚实的答案(至少对我来说不是很清楚)。我也读过教程,但没有用。我遗漏了什么?
发布于 2016-10-17 23:07:57
因此,Java非常正确地告诉您,您还没有实现抽象方法setThings
,它使用的是List<?>
,而不是List<T>
或List<String>
。所有这些都是不同的东西。见这个问题需要详细解释。
最简单的解决方案也是为抽象类引入一个泛型:
public abstract class MyClass<T> {
public abstract void setThings(List<T> things);
}
public class SubClass extends MyClass<String> {
private List<String> things;
public void setThings(List<String> things) {
this.things = things;
}
}
发布于 2016-10-17 22:58:21
List<?> things
是一个未知类型的列表。
List<T> things
是T
类型的列表。
这两件事是不一样的,这就是为什么你要得到编译错误。
要消除这一错误,有几种明智的方法:
Bar
也接受未知类型的列表
抽象类MyClass {公共抽象空虚setThings(列表事物;@重写公共抽象setThings(List things) ){ this.things = things;}https://stackoverflow.com/questions/40096908
复制相似问题