泛型问题和<e extends =“”... =“”>

时间:2016-04-23 21:13:41

标签: java generics

我有两个这样的课程

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给了我错误

  

Inlet类型中的方法addToStore(E)不适用于参数(电)

但是,由于在outputToAll E必须延长电量,所以Inlet至少是Inlet,为什么传递一个Electricity对象addToStore不起作用?

如果编译器不够聪明,不知道这会有效,那么什么是好的解决方法?

1 个答案:

答案 0 :(得分:2)

您不需要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));
        }
    }
    ...
}

由于Liskov substitution principle,此课程(可能,因为我无法看到其余部分)也适用于Electricity的子类。< / p>