You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 lines
800 B

public class AnimalTest {
public static void main(String[] args) {
// 创建动物数组,演示多态
Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();
// 测试多态调用makeSound方法
System.out.println("测试动物叫声:");
for (Animal animal : animals) {
animal.makeSound();
}
// 测试Dog的swim方法
System.out.println("\n测试游泳能力:");
if (animals[0] instanceof Swimmable) {
((Swimmable) animals[0]).swim();
}
if (animals[1] instanceof Swimmable) {
((Swimmable) animals[1]).swim();
} else {
System.out.println("猫不会游泳!");
}
}
}