繁体   English   中英

如果我将子类强制转换为其超类,并调用在子类中重写的方法,它是否执行重写或原始方法?

[英]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?

考虑:

DogAnimal的子类, Dog覆盖Animal.eat()

Animal[] animals = getAllAnimals();
for (int i = 0; i < animals.length; i++) {
    animals[i].eat();
}

如果Animal.eat()覆盖了Dog.eat() ,那么从Animal类型的标识符调用方法时会调用哪一个( animals[i] ?)

将调用子类方法。 这就是多态的美。

除非子类像这样调用超类,否则子类将是唯一的方法调用:

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

编码

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

会叫狗的eat 但要小心! 如果你有

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

你有一个Cat定义了一个额外的方法:

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

然后你使用它们:

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

这将打印“Just a a a a cute mouse”,而不是“Grabbed a MOUSE!”。 为什么? 因为多态只适用于方法调用中点左侧的对象。

它将调用子类中的版本。

如果您无法传递作为其超类的子类化对象并且未获得子类方法,那么继承将毫无用处!

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM