0
class Aliphatic<F> extends Organic<F>{}
class Hexane<G> extends Aliphatic<G>{}
public class Organic<E>{
    void react(E e){}
    static void main(String[] args){
        Organic<? extends Organic> compound = new Aliphatic<Organic>();
        compound.react(new Organic());
    }
}

Why can't I call react method with Organic argument? The generic type ot the reference <? extends Organic> says that the generic type of the instantiation canb either a Organic, or a subtype of Organic.

Is because the compiler doesn't know this instantiation generic type until runtime type an so, it does not bind any value to its generic criteria?

Why is this case working? Is this case the same?

public class WildcardCollection {
    public static void main (String[] args){
        WildcardCollection w = new WildcardCollection();
        w.myMethod(new Items("hola",1));     //Compile
        w.myMethod(new SubItems("nuevo",3)); //Compile
    }
    public <T extends Items> void myMethod(T a){ //Same as above
        System.out.println("hi: "+a);
    }
}
class SubItems extends Items {
    SubItems(){};
    SubItems(String s, int i){ super(s,i);}
}
class Items implements Comparable<Items> {
    private String name;
    private int value;

    public Items() {}

    public Items(String n, int i){ this.name = n; this.value = i;}
    public String getName(){ return this.name;}
    public int getValue(){ return this.value;}

    public String toString(){ return "(" + this.name + "-" + this.value + ")";}

    public int compareTo(Items i){
        return this.value - i.getValue();
    }
}
4

1 回答 1

2

很简单,如果你有一个泛型类型的对象,其类型参数T? extends X通配符实例化,那么你不能在对象上调用接受类型参数的方法,T因为编译器不能保证类型安全。但是,您可以调用返回的方法T(并将返回值分配给 type 的变量X)。在您的具体示例中,这看起来应该是安全的

Organic<? extends Organic> compound = new Aliphatic<Organic>();
compound.react(new Organic());

但请记住,编译器必须react根据声明类型 ( ? extends Organic) 匹配调用,它不能依赖于您在 RHS 上分配的内容。如果编译器允许这样做,那么它也必须允许

Organic<? extends Organic> compound = new Aliphatic<Hexane<?>>();
compound.react(new Organic());

这显然是不正确的——情况与

Collection<? extends Number> nums = new ArrayList<Float>();
nums.add(Integer.valueOf(1));

(除此之外,由于Organic是通用的,您需要说Organic<? extends Organic<?>>或类似的,而不仅仅是Organic<? extends Organic>

于 2012-10-15T15:39:18.157 回答