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.

33 lines
1.0 KiB

// AnimalTest.java
public class Main {
public static void main(String[] args) {
// 1. 创建对象
// 使用多态:父类引用指向子类对象
Animal dog = new Dog("旺财");
Animal cat = new Cat("咪咪");
System.out.println("--- 基础叫声测试 ---");
// 2. 调用叫声方法(多态体现)
dog.makeSound();
cat.makeSound();
System.out.println("\n--- 游泳能力测试 ---");
// 3. 游泳测试
// 狗会游泳:需要向下转型(或者直接判断)
if (dog instanceof Swimmable) {
Swimmable swimmingDog = (Swimmable) dog;
swimmingDog.swim();
} else {
System.out.println(dog.getName() + " 不会游泳");
}
// 猫不会游泳
if (cat instanceof Swimmable) {
Swimmable swimmingCat = (Swimmable) cat;
swimmingCat.swim();
} else {
System.out.println(cat.getName() + " 不会游泳");
}
}
}