简体   繁体   中英

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. 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? Eg.

animals[3].bark();

Iv'e tried to cast the element, I was examining to a Dog but to no avail Eg.

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

Option 1: Use instanceof (not recommended):

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

Option 2: Enhance Animal with abstract method:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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