From 03abada8b4ca84de6aafcd70bfa5f1da5f188bee Mon Sep 17 00:00:00 2001 From: GaoGeng <3123557312@qq.com> Date: Thu, 9 Apr 2026 17:07:04 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20'W6'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W6/Animal.java | 16 ++++++++++++++++ W6/Cat.java | 13 +++++++++++++ W6/Dog.java | 19 +++++++++++++++++++ W6/Main.java | 33 +++++++++++++++++++++++++++++++++ W6/Swimmable.java | 3 +++ 5 files changed, 84 insertions(+) create mode 100644 W6/Animal.java create mode 100644 W6/Cat.java create mode 100644 W6/Dog.java create mode 100644 W6/Main.java create mode 100644 W6/Swimmable.java diff --git a/W6/Animal.java b/W6/Animal.java new file mode 100644 index 0000000..a6514ed --- /dev/null +++ b/W6/Animal.java @@ -0,0 +1,16 @@ +// Animal.java +public abstract class Animal { + private String name; + + public Animal(String name) { + this.name = name; + } + + // 获取名字的方法 + public String getName() { + return name; + } + + // 抽象方法:发出叫声,强制子类实现 + public abstract void makeSound(); +} diff --git a/W6/Cat.java b/W6/Cat.java new file mode 100644 index 0000000..dee8423 --- /dev/null +++ b/W6/Cat.java @@ -0,0 +1,13 @@ +// Cat.java +public class Cat extends Animal { + + public Cat(String name) { + super(name); + } + + // 实现父类的抽象方法 + @Override + public void makeSound() { + System.out.println(this.getName() + ":喵喵喵!"); + } +} diff --git a/W6/Dog.java b/W6/Dog.java new file mode 100644 index 0000000..7007494 --- /dev/null +++ b/W6/Dog.java @@ -0,0 +1,19 @@ +// Dog.java +public class Dog extends Animal implements Swimmable { + + public Dog(String name) { + super(name); // 调用父类构造器 + } + + // 实现父类的抽象方法 + @Override + public void makeSound() { + System.out.println(this.getName() + ":汪汪汪!"); + } + + // 实现接口的游泳方法 + @Override + public void swim() { + System.out.println(this.getName() + " 正在狗刨式游泳..."); + } +} diff --git a/W6/Main.java b/W6/Main.java new file mode 100644 index 0000000..a552c3c --- /dev/null +++ b/W6/Main.java @@ -0,0 +1,33 @@ +// AnimalTest.java +public class Main { + public static void main(String[] args) { + // 1. 创建对象 + // 使用多态:父类引用指向子类对象 + Animal dog = new Dog("旺财"); + Animal cat = new Cat("咪咪"); + + System.out.println("--- 基础叫声测试 ---"); + // 2. 调用叫声方法(多态体现) + dog.makeSound(); + cat.makeSound(); + + System.out.println("\n--- 游泳能力测试 ---"); + + // 3. 游泳测试 + // 狗会游泳:需要向下转型(或者直接判断) + if (dog instanceof Swimmable) { + Swimmable swimmingDog = (Swimmable) dog; + swimmingDog.swim(); + } else { + System.out.println(dog.getName() + " 不会游泳"); + } + + // 猫不会游泳 + if (cat instanceof Swimmable) { + Swimmable swimmingCat = (Swimmable) cat; + swimmingCat.swim(); + } else { + System.out.println(cat.getName() + " 不会游泳"); + } + } +} diff --git a/W6/Swimmable.java b/W6/Swimmable.java new file mode 100644 index 0000000..d3b896f --- /dev/null +++ b/W6/Swimmable.java @@ -0,0 +1,3 @@ +public interface Swimmable { + void swim(); +}