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
There are two important concepts which are competing with each other here.
The first concept is static typing, which means the Java compiler checks the types of your expressions, variables and methods at compile-time, before the code ever gets a chance to run. In this case, the variable myAnimal is of type Animal, and the type Animal does not have a method bark(), so myAnimal.bark() is a type error.
The second concept is dynamic dispatch, which means that the method implementation is selected based on the type of the object at runtime. Since myAnimal holds a reference to an object of the class Dog, the call to the move() method invokes the implementation of that method provided in the Dog class.