Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this downcast not allowed in java?

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!

like image 425
rb612 Avatar asked Apr 08 '26 08:04

rb612


1 Answers

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.

like image 166
Eric J. Avatar answered Apr 10 '26 20:04

Eric J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!