[英]Wildcard and mutator methods
I was totally confused, when saw this snippet: 当看到以下片段时,我感到非常困惑:
class Animal {}
class Dog extends Animal {}
public class Test {
public static void main(String[] args) {
List<? super Animal> list = new ArrayList<>();
list.add(new Dog()); //it's OK
list.add(new Animal()); //and this is OK too
}
}
Why such things are allowed? 为什么允许这样的事情? When i changed my list to List<? super Dog> list = new ArrayList<>();
当我将列表更改为List<? super Dog> list = new ArrayList<>();
List<? super Dog> list = new ArrayList<>();
compile-time error occurs in list.add(new Animal());
list.add(new Animal());
发生编译时错误 With extends
wildcard all combinations cause errors. 使用extends
通配符时,所有组合都会导致错误。 Who can tell the exact reason of this behaviour? 谁能说出这种行为的确切原因? Thanks in advance. 提前致谢。
List<? super Animal> list = new ArrayList<>();
list.add(new Dog()); //it's OK
list.add(new Animal()); //and this is OK too
The above code is allowed as it should be : because A dog is also an animal. 上面的代码应被允许:因为狗也是动物。
List<? super Dog> list = new ArrayList<>();
list.add(new Dog()); //it's OK
list.add(new Animal()); //error
The above code is an error as it should be again, because not every animal is a dog. 上面的代码是错误的,应该再次出现,因为不是每只动物都是狗。
inheritance
is as simple as this. inheritance
就是这么简单。 :) :)
NOTE: To complete the answer I refer to this super good answer in : 注意:要完成答案,请参阅:
[ Difference between <? [ 之间的区别<? super T> and <? 超级T>和<? extends T> in Java 1 在Java 1中 扩展T>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.