+ 1
DownCasting
Hello... Please I'm a little bit confused by this statement: "But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance that some of these Animals are actually Dogs, so the process fails." Does it mean that, if we have for instance, Animal b = new Dog(); And doing this; ((Cat)b).makeSound(); will fail?
1 ответ
+ 3
Yes it will fail.
Think of it this way.
You are assigning the value, 'Dog' to the variable Animal. This is allowed, since a Dog is an Animal.
Then, you cast the variable to a Cat.
But it still has the value of Dog!!
A Cat is a Dog?! This is madness! Error!
That's why you may see things like this:
if(myAnimal instanceof Dog)
((Dog)myAnimal).makeSound();
else if(myAnimal instanceof Cat)
((Cat)myAnimal).makeSound();