我有两个这样的类(class)
public class Wire<E extends Electricity> implements Connection<E> {
private ArrayList<Inlet<E>> outlets = new ArrayList<Inlet<E>>();
public void outputToAll() {
for (Inlet<E> inlet : outlets){
inlet.addToStore(new Electricity(amountPer));
}
}
}
和
public abstract class Inlet<E> {
private E store;
public void addToStore(E inputObj){
this.store.add(inputObj);
}
}
Inlet 没有任何错误,但 Wire 给了我错误
The method addToStore(E) in the type Inlet is not applicable for the arguments (Electricity)
但是,由于outputToAll中的E必须扩展电力,因此Inlet至少是Inlet,为什么将Electricity对象传递给addToStore不起作用?
如果编译器不够聪明,无法知道这是否有效,那么什么是好的解决方法?
最佳答案
您不需要 Wire
类对于您想要做的事情是通用的。
如果你有:
public class Wire implements Connection<Electricity> {
private ArrayList<Inlet<Electricity>> outlets = new ArrayList<Inlet<Electricity>>();
public void outputToAll() {
for (Inlet<Electricity> inlet : outlets){
inlet.addToStore(new Electricity(amountPer));
}
}
...
}
这个类(可能,因为我看不到它的其余部分)也适用于 Electricity
的子类,因为 Liskov substitution principle .
关于java - 泛型和 <E extends ...> 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816496/