首页 > 解决方案 > 在运行时 Java 将对象转换为其特定类型

问题描述

假设我有以下类层次结构:

abstract class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}

考虑以下代码:

class Test {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Dog dog = new Dog();
        Animal animal = cat;
        
        talk(dog);
        talk(cat);
        talk(animal);
        
        List<Animal> list = new ArrayList();
        list.add(cat);
        list.add(dog);
        for(Animal animal : list)
            talk(animal);
    }

    public static void talk(Animal animal) {
        System.out.println("Animal");
    }
    
    public static void talk(Dog dog) {
        System.out.println("Dog");
    }
    
    public static void talk(Cat cat) {
        System.out.println("Cat");
    }
}

当我运行程序时,我得到输出

Dog
Cat
Animal
Animal
Animal

这意味着当使用 Animal 引用引用时,每只 Dog 和 Cat 都被视为没有特定种类的 Animal。如果我在编译时知道动物的具体种类,我可以将该动物转换为它的具体种类,并调度所需的谈话方法;但是如果给我一个动物列表并且我在编译时不知道它们的确切种类,我怎样才能让程序调用特定的谈话方法?

标签: javadispatch

解决方案


推荐阅读