Let's say I have a superclass of Animal
, and a subclass of Dog
.
We can upcast by saying:
Animal a = new Dog();
We CANNOT downcast by saying:
Dog b = new Animal();
So I do understand that an animal does not HAVE to be a dog. But, why would having an animal "blueprint" in a dog container throw an exception? Because Dog inherits methods from Animal, when we take this animal and put it into a dog container, we know Dog inherits/overrides all methods that Animal has, so why does Java not allow this?
Thank you!
Dog b = new Animal();
b.Woof();
Animal has no interface/method called Woof(). It does not know how to behave like a dog, but all dogs know how to behave like an animal.