0

I have code like this:

class Scratch {
    public static void main(String[] args) {
        List<Cat> cats = new ArrayList<>();

        List<? extends Animal> animals = cats;

        animals.add(new Cat()); // compile error

        Animal animal = animals.get(0);
    }
}

class Animal {

}

class Cat extends Animal {

}

class Dog extends Animal {

}

Why cannot add a Cat instance to animals? Add Cat instance or Dog instance to animals, and read elements as animal is type safe. I know PECS (short for "Producer extends and Consumer super"), but I can't understand that why can't write in covariance and cant't read in contravariance in Java.

Ryanqy
  • 8,476
  • 4
  • 17
  • 27

1 Answers1

0

<? extends Animal> is not Cat, it can be any subclass ot Animal, for example:

List<? extends Animal> dogs = new ArrayList<Dog>();
dogs.add(new Cat()); // compile error

No matter what actually type <? extends Aminal> is, it can't add any subclass of Animal. Use List<Animal> instead of List<? extends Animal>.

zhh
  • 2,346
  • 1
  • 11
  • 22