Upcasting/Downcasting in Java

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

    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!

提交回复
热议问题