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<>();
compile-time error occurs in list.add(new Animal());
With extends
wildcard all combinations cause errors. 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. :)
NOTE: To complete the answer I refer to this super good answer in :
[ Difference between <? super T> and <? extends T> in Java 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.