I am trying to understand Java\'s polymorphism, and I have one question about downcasting an object. Let\'s say for this example I have two subclasses Dog and Cat that inher
You should only cast to a class that the object really is, so if you have a Dog
that extends Animal
you can cast it to an Animal
(because it is one) but you shouldn't cast an Animal
to a Dog
because not all Animal
s are Dog
s. The Dog
class may well have extra fields that are not implemented by the Animal
class and so the cast doesn't make sense (what do you initialise those values to?).