繁体   English   中英

为什么这个泛型引用不能指向Java中的这个类似扩展类?

[英]Why this generic reference can't point to this similar extended class in Java?

为什么这个泛型引用不能指向Java中的这个类似扩展类?

http://goo.gl/evqOcP

public class HelloWorld{

    public static void main(String []args){

        Interface<Integer,Object> test = new Test();

        System.out.println(test.method(test));
    }
}


public interface Interface<A, B extends Object> {
    public A method(B param);
}

public class Test implements Interface<Integer,Test> {
    private int a = 0;

    public Integer method(Test param){
        return param.a;
    }
}

编译时出现此错误

HelloWorld.java:5: error: incompatible types                                                                                                                         
        Interface<Integer,Object> test = new Test();                                                                                                                 
                                         ^                                                                                                                           
  required: Interface<Integer,Object>                                                                                                                                
  found:    Test                                                                                                                                                     
1 error  

您的Test类实现Interface<Integer,Test> ,但是您将其声明为Interface<Integer, Object>类型,因此类型不匹配。

您可以将参考/分配更改为:

Interface<Integer, Test> test = new Test();

另外请注意,您将无法调用method(test)test ,因为该方法需要一个Test参数,而不是一个Interface<...>参数。

Test类实现Interface<Integer,Test> ,并且类型声明为Interface<Integer,Object> 不允许此分配,因为泛型是invariant

Interface<Integer,Test>既不是Interface<Integer,Object>的子类型也不是父类型。 因此,不能将Interface<Integer,Test>分配给Interface<Integer,Object>

您可以按以下方式更改赋值语句以使其起作用:

Interface<Integer, ? extends Test> test = new Test();

这样想,假设class Animalclass Dog extends Animalclass Elephant extends Animal

现在您有了一个可以容纳Dogs的狗窝, List<Dog> kennel并且还有一个动物园: List<Animal> zoo

狗窝是一种动物园吗? 不可以,您不能add大象add到狗窝中。

动物园是一种狗窝吗? 不,你不能保证当你它只返回狗get来自它。

因此,正如在其他答案中提到的那样,两个通用容器之间没有子类型关系,因此分配失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM