package main.w6; // 1. 抽象动物类 abstract class Animal { // 抽象方法:动物叫声 public abstract void makeSound(); } // 2. 游泳接口 interface Swimmable { void swim(); } // 3. Dog类:继承Animal,实现Swimmable接口 class Dog extends Animal implements Swimmable { @Override public void makeSound() { System.out.println("小狗汪汪叫~"); } @Override public void swim() { System.out.println("小狗会狗刨游泳"); } } // 4. Cat类:仅继承Animal,不实现Swimmable class Cat extends Animal { @Override public void makeSound() { System.out.println("小猫喵喵叫~"); } } // 测试类 public class AnimalTest { public static void main(String[] args) { // 多态调用:父类引用指向子类对象 Animal dog = new Dog(); Animal cat = new Cat(); // 调用叫声方法 System.out.println("=== 动物叫声 ==="); dog.makeSound(); cat.makeSound(); // 只有实现了Swimmable的对象才能调用swim() System.out.println("\n=== 游泳能力 ==="); if (dog instanceof Swimmable) { ((Swimmable) dog).swim(); } // cat没有实现Swimmable,不能调用swim() System.out.println("小猫不会游泳"); } }