【问题标题】:Calling a Method of a Subclass From an Array of the Superclass从超类的数组中调用子类的方法
【发布时间】:2016-02-23 17:44:34
【问题描述】:

考虑以下问题。 你有一个 Dog 类和一个 Cat 类,它们都扩展了 Animal 类。 如果您创建一个动物数组,例如。

Animal[] animals = new Animal[5];

在这个数组中 5 随机猫和狗被设置到每个元素。 如果 Dog 类包含方法 bark() 而 Cat 类不包含,那么根据数组​​如何调用该方法?例如。

animals[3].bark();

我试图投射元素,我正在检查 Dog 但无济于事,例如。

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

【问题讨论】:

    标签: java arrays class casting hierarchy


    【解决方案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
        }
    }
    

    【讨论】:

    • 非常感谢,原来我的投射方式不正确 (Dog(animals[3])).bark();((Dog)animals[3]).bark();
    猜你喜欢
    • 2017-05-13
    • 2011-11-22
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多