I am trying to understand upcasting and downcasting in Java and I am confused by the following scenario (about my code, which is below):
First - why is it that the
Here you declared the myAnimal as Animal and every animal can't bark! i.e myAnimal is referring to Animal here.
Animal myAnimal = myDog;
But for sure Dog is an animal which can bark, hence you need to explicitly cast your myAnimal by letting JVM know its of type Dog and not Just Animal.
So if you change //myAnimal.bark(); to below it will work!
((Dog) myAnimal).bark();
Here we casted myAnimal from Animal to Dog. hence bark() method is allowed and it does not give any compilation issue.
Hope this helps!