从超类数组中调用子类的方法

时间:2015-11-21 05:56:09

标签: java arrays class casting hierarchy

请考虑以下事项。 你有一个Dog Class和一个Cat Class,它们都扩展了Class Animal。 如果你创建一个动物数组。

Animal[] animals = new Animal[5];

在此数组 5 中,随机的Cats and Dogs设置为每个元素。 如果Dog Class包含方法bark()而Cat类没有,那么如何根据数组调用此方法?例如

animals[3].bark();

Iv'e试图施放元素,我正在检查一只狗,但无济于事。

(Dog(animals[3])).bark();

1 个答案:

答案 0 :(得分:1)

选项1:使用instanceof(不推荐):

if (animals[3] instanceof Dog) {
    ((Dog)animals[3]).bark();
}

选项2:使用抽象方法增强Animal

public abstract class Animal {
    // other stuff here
    public abstract void makeSound();
}
public class Dog extends Animal {
    // other stuff here
    @Override
    public void makeSound() {
        bark();
    }
    private void bark() {
        // bark here
    }
}
public class Cat extends Animal {
    // other stuff here
    @Override
    public void makeSound() {
        meow();
    }
    private void meow() {
        // meow here
    }
}
相关问题