If I included a subclass as my superclass and called a method that was overridden in the subclass, does it execute 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() overridden by Dog.eat() , which is called when the method is called from an identifier of type Animal ( animals[i] ?)

+4
source share
5 answers

The subclass method will be called. This is the beauty of polymorphism .

+9
source

A subclass will be the only method call if the subclass does not call the superclass this way:

 class Dog { public eat() { super.eat(); } } 
+2
source

The code

 Animal a = new Dog(); a.eat(); 

will call the Dog eat method. But be careful! If you

 class Animal { public void eat(Animal victim) { System.out.println("Just ate a cute " + victim.getClass().getSimpleName()); } } 

and you have Cat, which defines an additional method:

 class Cat extends Animal { public void eat(Mouse m) { System.out.println("Grabbed a MOUSE!"); } } 

and then you use them:

 Animal cat = new Cat(); Animal mouse = new Mouse(); cat.eat(mouse); 

This will print β€œJust ate a cute mouse,” not β€œGrabbed a MOUSE!”. What for? Because polymorphism only works for the object to the left of the point in the method call.

+2
source

It will invoke the version in the subclass.

Inheritance would be pretty useless if you could not pass the object of the subclass, which would be its superclass, and not get the method of the subclass!

+1
source

A sscce

 /** * @author fpuga http://conocimientoabierto.es * * Inheritance test for http://stackoverflow.com/questions/10722447/ * */ public class InheritanceTest { public static void main(String[] args) { Animal animals[] = new Animal[2]; animals[0] = new Animal(); animals[1] = new Dog(); for (int i = 0; i < animals.length; i++) { animals[i].eat(); if (animals[i] instanceof Dog) { System.out.println("!!Its a dog instance!!"); ((Dog) animals[i]).eat(); } } } private static class Animal { public void eat() { System.out.println("I'm an animal"); } } private static class Dog extends Animal { @Override public void eat() { System.out.println("I'm dog"); } } } 
0
source

Source: https://habr.com/ru/post/1413961/


All Articles