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.
36 lines
1.3 KiB
36 lines
1.3 KiB
// 测试类:主方法
|
|
public class AnimalTest {
|
|
public static void main(String[] args) {
|
|
// 1. 多态:用父类引用指向子类对象
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
System.out.println("=== 动物叫声测试 ===");
|
|
// 多态调用:根据实际对象类型执行对应方法
|
|
dog.makeSound(); // 输出:汪汪汪!
|
|
cat.makeSound(); // 输出:喵喵喵!
|
|
|
|
System.out.println("\n=== 游泳功能测试 ===");
|
|
// 2. 类型判断:只有Dog能游泳,Cat不能
|
|
if (dog instanceof Swimmable) {
|
|
Swimmable swimmableDog = (Swimmable) dog;
|
|
swimmableDog.swim(); // 输出:狗在水里欢快地游泳~
|
|
}
|
|
|
|
if (cat instanceof Swimmable) {
|
|
// Cat 不实现 Swimmable,所以这段代码不会执行
|
|
Swimmable swimmableCat = (Swimmable) cat;
|
|
swimmableCat.swim();
|
|
} else {
|
|
System.out.println("猫不会游泳~");
|
|
}
|
|
|
|
System.out.println("\n=== 数组多态遍历 ===");
|
|
// 3. 用数组存储多个动物,统一调用
|
|
Animal[] animals = {new Dog(), new Cat()};
|
|
for (Animal animal : animals) {
|
|
animal.makeSound();
|
|
}
|
|
}
|
|
}
|
|
|
|
|