0

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<>();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.

Dmytro
  • 1,590
  • 2
  • 11
  • 18

1 Answers1

1
    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 Java1

Community
  • 1
  • 1
nafas
  • 5,004
  • 1
  • 23
  • 47
  • Of course! Thanks. But what about `extends`? Why we cannot put `Dog` in `List extends Dog>`? – Dmytro Feb 26 '15 at 16:54
  • @Jskyi I think this is what you are asking abt mate [http://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java] – nafas Feb 26 '15 at 17:01