gpt4 book ai didi

java - 为什么第二个例子编译成功

转载 作者:行者123 更新时间:2023-12-01 18:04:28 26 4
gpt4 key购买 nike

import java.util.*;    

class Test
{
public static class Base
{
}

public static class Derived1
extends Base
{
}

public static class Derived2
extends Base
{
}

public static void main (String[] args)
{
//Example1.
List<? extends Base> e = new ArrayList<Base>();
e.add(new Derived1()); //this won't compile

//Example2.
List<? super Base> b = new ArrayList<Base>();
b.add(new Derived1()); //this compiles
}
}

最佳答案

List<? super Base> b可以分配 List<Base>List<Object> 。一个Derived1实例可以添加到两者中,因此 b.add(new Derived1())语句通过编译。

另一方面,List<? extends Base> e可能会被分配一个List<Derived2> ,因此编译器不允许添加 Derived1它的实例。

关于java - 为什么第二个例子编译成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com