I have classes:
class Animal{
public void type(){
System.out.println("I am Animal");
}
}
class Dog extends Animal{
public void type(){
System.out.println("I am Dog");
}
}
class Cat extends Animal{
public void type(){
System.out.println("I am Cat");
}
}
class Haski extends Dog{
public void type(){
System.out.println("I am Haski");
}
}
and I create List
with wildcards
:
List<? extends Animal> animalList = new ArrayList<Animal>();
I know that I can not add some object to animalList
. I read about it in different books, articles in internet, video lessons, but I still not understand why? If we knot that animalList
contains only objects extends Animal
why java can not add any objects extends Animal
and cast it to Animal
?
animalList.add(new Dog()); //cast dog to Animal
animalList.add(new Cat()); //cast cat to Animal
Compiler has enougth information - objects extends Animal
why it can not cast?
EDIT:
So I do not understand rightly.
List<Animal> animalList1 = new ArrayList<Animal>();
animalList.add(new Animal());
animalList.add(new Dog());
animalList.add(new Cat());
animalList.add(new Haski());
and
List<? extends Animal> animalList
There is a feeling that they should be the same. But I can not feel the difference in principle