// 1. 创建抽象类 Animal abstract class Animal { // 包含抽象方法 makeSound() public abstract void makeSound(); } // 2. 创建接口 Swimmable interface Swimmable { // 包含方法 swim() void swim(); } // 3. 创建 Dog 类继承 Animal 并实现 Swimmable class Dog extends Animal implements Swimmable { @Override public void makeSound() { System.out.println("Dog: 汪汪汪 (Woof Woof)"); } @Override public void swim() { System.out.println("Dog: 狗狗正在游泳 (Dog is swimming)"); } } // 4. 创建 Cat 类继承 Animal (不实现 Swimmable) class Cat extends Animal { @Override public void makeSound() { System.out.println("Cat: 喵喵喵 (Meow Meow)"); } } // 5. 主类用于测试 public class AnimalTest { public static void main(String[] args) { // --- 测试 Dog --- // 多态调用:父类引用指向子类对象 Animal myDog = new Dog(); myDog.makeSound(); // 调用 Dog 的叫声 // 因为 myDog 是 Animal 类型,无法直接调用 swim,需要向下转型或使用接口引用 // 这里演示接口多态 Swimmable swimmingDog = new Dog(); swimmingDog.swim(); // 调用 Dog 的游泳方法 System.out.println("----------------"); // --- 测试 Cat --- Animal myCat = new Cat(); myCat.makeSound(); // 调用 Cat 的叫声 // 注意:Cat 不能转换为 Swimmable,否则会报 ClassCastException } }