Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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]?)

like image 200
user1412893 Avatar asked Dec 09 '22 00:12

user1412893


1 Answers

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

like image 144
Ted Hopp Avatar answered May 01 '23 12:05

Ted Hopp