java - 在运行时 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。如果我在编译时知道动物的具体种类,我可以将该动物转换为它的具体种类,并调度所需的谈话方法;但是如果给我一个动物列表并且我在编译时不知道它们的确切种类,我怎样才能让程序调用特定的谈话方法?
解决方案
推荐阅读
- java - 在 BottomDialogFragment 我有使 Draggble 为假但它收到警告消息
- cassandra - Cassandra JVM 约束
- android - sdk 22 和 25 之间的 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION 权限有什么区别吗?
- javascript - Is it a good idea to use the "setState" function in JavaScript even if the previous state is irrelevant?
- python - seaborn swarmplot 中的水平图
- css - css INLINE-BLOCK div 居中对齐但保持内部元素仍左对齐
- node.js - 异步/等待错误返回 Promise {
} - powershell - 如何在 PowerShell 中返回自定义错误级别?
- mysql - 如何删除 SQL 中的重复(两行混合)行?
- node.js - 基于 swagger 文件验证请求的独立 NPM 库