// 测试类:main方法,测试多态调用 public class TestAnimal { public static void main(String[] args) { System.out.println("=== 1. 多态调用Animal父类引用 ==="); // 父类引用指向子类对象(多态核心) Animal dog = new Dog(); Animal cat = new Cat(); // 多态调用makeSound():运行时自动执行子类的方法 dog.makeSound(); // 输出:汪汪汪! cat.makeSound(); // 输出:喵喵喵! System.out.println("\n=== 2. 测试Dog的游泳能力(接口多态) ==="); // 接口引用指向实现类对象(接口多态) Swimmable swimmableDog = new Dog(); swimmableDog.swim(); // 输出:小狗在水里游泳~ System.out.println("\n=== 3. 类型判断与向下转型(可选拓展) ==="); // 判断Animal对象是否能游泳(instanceof) if (dog instanceof Swimmable) { System.out.println("Dog是可游泳的"); // 向下转型为Swimmable,调用swim方法 ((Swimmable) dog).swim(); } if (cat instanceof Swimmable) { System.out.println("Cat是可游泳的"); } else { System.out.println("Cat不会游泳"); } } }