-4

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?
rakesh mehra
  • 618
  • 1
  • 9
  • 21

1 Answers1

0

This is what Java gives you as Runtime Polymorphism, at runtime what is the object reference it has, that method instance will be called.

Think that you are writing some generic lib/framework then all you want use is Animal class which is base to all other sub classes like Dog, Cat etc then you can not declare your members like Dog myDog or Cat myCat there it should be Animal myAnimal so that it can take all the animal subclasses.

Thast's why animalArrayList should always take Animal and its variants no compilation error comes.

You never know Animal class can be extended by your lib users to create many other Animal classes.

Pavan
  • 819
  • 6
  • 18