Search code examples
javadowncast

What is the purpose of downcasting and upcasting at the same time?


I have a parent class Animal and a child class Dog extends Animal.

Dog dog = new Dog();
Animal animal1 = (Dog) dog;
Animal animal2 = (Animal) dog;

I just learned about downcasting and I'd like to ask what is the purpose of doing downcasting and upcasting at the same time?


Solution

  • Does Dog inherit from Animal? I will assume yes.

    To answer the question - There is no point to do that. It can be simplified such as:

    Dog dog = new Dog();
    Animal animal1 = dog;
    Animal animal2 = dog;
    

    You may want to downcast when the variables (animal1 or animal2) are from type Dog and you have an object from another type that Dog inherits from (e.g. Animal) - but be sure that that object really is Dog.