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?

做~自己de王妃 提交于 2021-01-27 07:10:52

问题


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


回答1:


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




回答2:


The subclass will be the only method call, unless the subclass calls the superclass like this:

class Dog {
  public eat() {
     super.eat();
  }
}



回答3:


The code

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

will call Dog's eat method. But beware! If you had

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

and you have a Cat that 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", and not "Grabbed a MOUSE!". Why? Because polymorphism only works for the object to the left of the dot in a method invocation.




回答4:


It'll call the version in the subclass.

Inheritance would be pretty useless if you couldn't pass around a subclassed object cast as its superclass and not get the subclassed method!




回答5:


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");
    }
    }

}


来源:https://stackoverflow.com/questions/10722447/if-ive-cast-a-subclass-as-its-superclass-and-call-a-method-that-was-overridden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!