我明白了嗎?擴展..和?超..對自己和泛型類型是可能的,但我只是不明白下面是如何可能的這個層次的工作:結合<?擴展ClassE>和<?超級ClassB>
- >表示延伸
類是X(最低),A到E(最高)
接口是F
X - > A(實施F) - >乙 - 「ç - > E(實現F)
也d - >電子
public class Node<T extends ClassE> {
private T info;
public T getInfo() {
return info;
}
public void setInfo(T info) {
this.info = info;
}
}
public static void main (String [] args){
Node<? super ClassB> n2 = new Node<ClassC>();
// this makes sense, since Node accepts below E and above B
InterfaceF i2 = n2.getInfo();
// how? Not only outside of <? extends E> but also getting value even though
// <? super B> is defined above, what's up with PECS?
n2.setInfo(new ClassX());
// also.. how? I'm setting a class that's out of the allowed range +
// seemingly violating the PECS for <? extends E>
}
正如你所看到的,當我們將它們組合起來時,我感到非常困惑,而讓我感到驚訝的是讓這些聲明通過編譯器沒有問題。 我在某處讀過兩種邊界的組合在Java中都是不可能的,但是那又如何呢?
你確定這個'Node <?超級ClassB> n2 =新節點();'編譯?參考n2需要參數類型爲B或更高的'Node',而您試圖在繼承層次上傳遞比B低的B. –
matoni
我沒有指定任何值來測試它,但我完全能夠執行程序,我100%確定 – mxOx2kL
關於層次結構,E是最高的,X是最低的,對於混淆抱歉。 所以A擴展B,B擴展C,C擴展E – mxOx2kL