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.

25 lines
1005 B

// 测试类:主程序入口,测试多态调用
public class AnimalTest {
public static void main(String[] args) {
// 多态:父类引用指向子类对象
Animal dog = new Dog();
Animal cat = new Cat();
// 1. 测试动物叫声的多态调用
System.out.println("=== 动物叫声测试 ===");
dog.makeSound(); // 执行Dog类的makeSound()
cat.makeSound(); // 执行Cat类的makeSound()
// 2. 测试游泳能力(只有Dog实现了Swimmable)
System.out.println("\n=== 游泳能力测试 ===");
// 判断dog是否实现了Swimmable接口,避免转型异常
if (dog instanceof Swimmable) {
Swimmable swimmableDog = (Swimmable) dog;
swimmableDog.swim(); // 执行Dog类的swim()
}
// Cat没有实现接口,无法调用swim()
if (!(cat instanceof Swimmable)) {
System.out.println("猫不会游泳");
}
}
}