-1

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?

lotan
  • 53
  • 5
  • 4
    Where exactly does your example code downcast and upcast at the same time? – tkausl Jun 23 '19 at 10:25
  • 1
    please check the below link https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class/23414798#23414798 – Arun Prasat Jun 23 '19 at 10:26
  • 3
    The casts in your code are unnecessary. – Sweeper Jun 23 '19 at 10:26
  • 1
    I'm not sure what your code has to do with your question, but in any case, both explicit casts in that code are unnecessary. – RealSkeptic Jun 23 '19 at 10:26
  • 1
    1. There is no downcast here. 2. Neither typecast has any point whatsoever. The first one merely asserts the *status quo,* and the second one is redundant. – user207421 Jun 23 '19 at 10:27

1 Answers1

0

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.

Stav Alfi
  • 13,139
  • 23
  • 99
  • 171