If I've cast a subclass as its superclass, and call a method that was overridden in the subclass, does it perform the overridden or original method?

casting, inheritance, java, oop

Solution

The subclass method will be called. That's the beauty of polymorphism.

Problem

Consider: `Dog` is a subclass of `Animal`, and `Dog` overrides `Animal.eat()` ``` Animal[] animals = getAllAnimals(); for (int i = 0; i < animals.length; i++) { animals[i].eat(); } ``` If `Animal.eat()` is overriden by `Dog.eat()`, which one is called when the method is called from an identifier of type `Animal` (`animals[i]`?)

Original source