I have been banging my head to understand the real use of Object type casting in java and why it is even there. See example below.
My question is in the form of comments below.
Please don't suggest me to go reach somewhere. I have already done that. Please answer me directly if you know. Thanks.
Check this code with method 'scream' overridden I am not getting compile time error. Watch comments too
Animal aniObj = new Animal();
Animal dogAniObj = new Dog();
Dog dogObj = new Dog();
ArrayList<Animal> animalArrayList = new ArrayList<Animal>();
animalArrayList.add(aniObj);
animalArrayList.add(dogAniObj);
animalArrayList.add(dogObj);//Here when I am able to add the Dog object there no point in creating dogAniObj above
aniObj.scream();//Calls scream of Animal
dogAniObj.scream();//Calls scream of Dog
dogObj.scream();//Calls scream of Dog. Then why do i need above statement? Why to attain polymorphic behavior when we can directly call scream method with the Dog object when needed?