Upcasting/Downcasting in Java

前端 未结 3 1643
夕颜
夕颜 2021-01-07 14:02

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

3条回答
  •  爱一瞬间的悲伤
    2021-01-07 14:08

    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.

提交回复
热议问题