ArrayList<Animal> animal = new ArrayList<Cat>(); //if this was allowed then following will create problems
animal.add(new Dog()); //Oops we added a Dog into a Cat List
In addition to this
if
ArrayList<Animal> animal = new ArrayList<Animal>();
then
animal.add(new Dog());
animal.add(new Cat()); allowed
Why
ArrayList<Animal> animal = new ArrayList<Cat>(); not allowed ?
As JVM has not runtime information about type of ArrayList, JVM will only knows that it is just an ArrayList means jvm will see this code:
ArrayList animal=new ArrayList();
and this code can take any object. So to avoid above condition mentioned by Ankit, compiler only allows type-safe conversions, such that ArrayList<Cat> can not contain
new Dog();. Think in terms of compiler, you will grasp it easily. Again read K&B book for this topic and do some meditation over this.