Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 具有超级_Java_Generics_Super - Fatal编程技术网

Java 具有超级

Java 具有超级,java,generics,super,Java,Generics,Super,在 公共类有机{ 无效反应(E){ } 静态void main(字符串[]参数){ 有机编译器不能查看化合物的实际值,只能查看它的声明。?可以是Elem2本身。它不允许你调用有机反应(Elem)列表中的有界通配符可以捕获Elem2及其任何超类型。由于Elem2扩展了Elem,这意味着当前可通过列表捕获的唯一类型是: public class Organic<E> { void react(E e) { } static void main(String[]

公共类有机{
无效反应(E){
}
静态void main(字符串[]参数){

有机编译器不能查看化合物的实际值,只能查看它的声明。
可以是
Elem2
本身。它不允许你调用
有机反应(Elem)

列表中的有界通配符可以捕获Elem2及其任何超类型。由于Elem2扩展了Elem,这意味着当前可通过列表捕获的唯一类型是:

public class Organic<E> {
    void react(E e) {
    }

    static void main(String[] args) {
        Organic<? super Elem2> compound = new Organic<Elem>();
        compound.react(new Elem());
    }
}

class Elem {}

class Elem2 extends Elem {}
列表
列表
列表
这应该行得通

List<Elem2>
List<Elem>
List<Object>
有机化合物=新的有机化合物();
这将不起作用,因为它们是通配符(分配工作、调用react将不起作用)

有机化合物=新的有机化合物();

有机通过使用super,您定义了类型参数的下限。您说的是,您的有机对象的实际类型是Elem2类型或其超类型之一。因此,编译器将替换Elem2的react方法的签名,如下所示

<F> void react(F e) {
}
因此,不能将新的Elem()传递给对象,因为它需要向下转换

也就是说,您不能这样做,原因与您不能将数字传递给需要整数的方法相同。如果应用向下转换,问题就解决了

void react(Elem2 value) {}
publicstaticvoidmain(字符串[]args){
全部有机=新有机();
有机的
<F> void react(F e) {
}
void react(Elem2 value) {}
public static void main(String[] args) {
    Organic<Object> all = new Organic<Object>();
    Organic<? super Elem2> other = all;

    Elem a = new Elem2();
    other.react((Elem2)a);
}
    Organic<? super Elem> other = ...;