简体   繁体   English

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

[英]Calling a Method of a Subclass From an Array of the Superclass

Consider the following. 考虑以下。 You have a Dog Class and a Cat Class, that both extend the Class Animal. 您有一个狗类和一个猫类,它们都扩展了动物类。 If you create an array of Animals Eg. 如果您创建一个动物类数组。

Animal[] animals = new Animal[5];

In this array 5 random Cats and Dogs are set to each element. 在此数组中,每个元素设置5个随机的猫和狗。 If the Dog Class contains the method bark() and the Cat Class does not, how would this method be called in terms of the array? 如果Dog类包含bark()方法,而Cat类不包含方法,则如何根据数组调用此方法? Eg. 例如。

animals[3].bark();

Iv'e tried to cast the element, I was examining to a Dog but to no avail Eg. Iv'e试图投射元素,我正在检查一只狗,但无济于事。

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

Option 1: Use instanceof (not recommended): 选项1:使用instanceof (不推荐):

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

Option 2: Enhance Animal with abstract method: 选项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
    }
}

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

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