I’m learning generics in Java, and I am learning Covariance and contravariance. I understood covariance and why can’t we write in to covariance type. But for me contravariance is confusing. I want to know why reading from contravariance is always Object type
Lets say we have the following classes
Class Animal
Class Dog extends Animal
Class Tiger extends Animal
Now, consider the following code
List<Animal> animals = new ArrayList<>();
List<? super Animal> contraVarianceList=animals;
animals.add(new Dog()); // Allowed
animals.add(new Tiger()); //Allowed
Animal animal = contraVarianceList.get(0); // Not allowed. Why?
My question is why cant we read “Animal” from the contravariance list. Why is it always and only “Object” that can be returned? What will or may go wrong if we read “Animal” from the contravariance list?