From 061b69a1e56e076344ac1921ed4455f785d6df28 Mon Sep 17 00:00:00 2001 From: ZhengShiyi <1980003269@qq.com> Date: Thu, 9 Apr 2026 20:03:48 +0800 Subject: [PATCH] =?UTF-8?q?W6=E4=BD=9C=E4=B8=9A=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W6/W6作业.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 W6/W6作业.java diff --git a/W6/W6作业.java b/W6/W6作业.java new file mode 100644 index 0000000..d0f3ecb --- /dev/null +++ b/W6/W6作业.java @@ -0,0 +1,60 @@ +// 动物叫声系统 + +// 抽象类 Animal +abstract class Animal { + // 抽象方法 makeSound() + public abstract void makeSound(); +} + +// 接口 Swimmable +interface Swimmable { + void swim(); +} + +// 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 is swimming"); + } +} + +// Cat 类继承 Animal,但不实现 Swimmable 接口 +class Cat extends Animal { + @Override + public void makeSound() { + System.out.println("Cat: Meow! Meow!"); + } +} + +// 测试类 +public class W6作业 { + public static void main(String[] args) { + // 测试多态调用 + Animal animal1 = new Dog(); + Animal animal2 = new Cat(); + + System.out.println("Testing polymorphic calls:"); + animal1.makeSound(); + animal2.makeSound(); + + // 测试 Swimmable 接口 + System.out.println("\nTesting Swimmable interface:"); + if (animal1 instanceof Swimmable) { + ((Swimmable) animal1).swim(); + } else { + System.out.println("Dog cannot swim"); + } + + if (animal2 instanceof Swimmable) { + ((Swimmable) animal2).swim(); + } else { + System.out.println("Cat cannot swim"); + } + } +} \ No newline at end of file