Upcasting/Downcasting in Java

前端 未结 3 1624
夕颜
夕颜 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:19

    With the implicit upcast at this line:

    Animal myAnimal = myDog;
    

    You are not doing anything to change the underlying instance myDog. What you are doing is assigning it to a variable of a type one level higher in the inheritance tree. Effectively, this restricts which methods can be called to only those defined in Animal, but does not change how those methods resolve.

    Because you have restricted the methods available to only those defined on the parent class Animal, the compiler cannot resolve Dog#bark(), since it is a method of Dog, and the variable myAnimal is defined to be of type Animal which has no #bark method.

    #move() is a method of both Animal and Dog, so it resolves, but it resolves to the method defined on Dog, since myAnimal still refers to an instance of Dog, despite being upcast.

提交回复
热议问题