From 012ea6456e0144c016f93e3ef25225013a41dd17 Mon Sep 17 00:00:00 2001 From: Mengxinyao Date: Wed, 15 Apr 2026 23:54:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(w6):W6-=E5=AD=9F=E9=91=AB=E5=9E=9A-2025060?= =?UTF-8?q?10204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w6/AnimalSystem.java | 52 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 w6/AnimalSystem.java diff --git a/w6/AnimalSystem.java b/w6/AnimalSystem.java new file mode 100644 index 0000000..b15ff96 --- /dev/null +++ b/w6/AnimalSystem.java @@ -0,0 +1,52 @@ +// 抽象类 Animal,包含抽象方法 makeSound() +abstract class Animal { + public abstract void makeSound(); +} + +// 接口 Swimmable,包含方法 swim() +interface Swimmable { + void swim(); +} + +// Dog 类继承 Animal 并实现 Swimmable 接口 +class Dog extends Animal implements Swimmable { + @Override + public void makeSound() { + System.out.println("汪汪!"); + } + + @Override + public void swim() { + System.out.println("狗在游泳!"); + } +} + +// Cat 类继承 Animal,不实现 Swimmable 接口 +class Cat extends Animal { + @Override + public void makeSound() { + System.out.println("喵喵!"); + } +} + +// 测试类,包含 main 方法用于测试多态调用 +public class AnimalSystem { + public static void main(String[] args) { + // 创建 Dog 和 Cat 实例 + Animal dog = new Dog(); + Animal cat = new Cat(); + + // 多态调用:通过 Animal 类型引用调用子类的 makeSound 方法 + dog.makeSound(); // 输出:汪汪! + cat.makeSound(); // 输出:喵喵! + + // 测试 Dog 是否可以游泳(Swimmable 接口) + if (dog instanceof Swimmable) { + ((Swimmable) dog).swim(); // 输出:狗在游泳! + } + + // Cat 不实现 Swimmable,不能调用 swim() 方法 + // 下面这行会报错:cat 不是 Swimmable 类型 + // ((Swimmable) cat).swim(); + } +} \ No newline at end of file