diff --git a/w6/Animal.class b/w6/Animal.class new file mode 100644 index 0000000..6d2fbb7 Binary files /dev/null and b/w6/Animal.class differ diff --git a/w6/Animal.java b/w6/Animal.java new file mode 100644 index 0000000..64adb08 --- /dev/null +++ b/w6/Animal.java @@ -0,0 +1,5 @@ +// 抽象类:动物,定义所有动物的通用行为 +public abstract class Animal { + // 抽象方法:发出声音,没有方法体,由子类实现 + public abstract void makeSound(); +} \ No newline at end of file diff --git a/w6/AnimalTest.class b/w6/AnimalTest.class new file mode 100644 index 0000000..b56c061 Binary files /dev/null and b/w6/AnimalTest.class differ diff --git a/w6/AnimalTest.java b/w6/AnimalTest.java new file mode 100644 index 0000000..57a543f --- /dev/null +++ b/w6/AnimalTest.java @@ -0,0 +1,25 @@ +// 测试类:主程序入口,测试多态调用 +public class AnimalTest { + public static void main(String[] args) { + // 多态:父类引用指向子类对象 + Animal dog = new Dog(); + Animal cat = new Cat(); + + // 1. 测试动物叫声的多态调用 + System.out.println("=== 动物叫声测试 ==="); + dog.makeSound(); // 执行Dog类的makeSound() + cat.makeSound(); // 执行Cat类的makeSound() + + // 2. 测试游泳能力(只有Dog实现了Swimmable) + System.out.println("\n=== 游泳能力测试 ==="); + // 判断dog是否实现了Swimmable接口,避免转型异常 + if (dog instanceof Swimmable) { + Swimmable swimmableDog = (Swimmable) dog; + swimmableDog.swim(); // 执行Dog类的swim() + } + // Cat没有实现接口,无法调用swim() + if (!(cat instanceof Swimmable)) { + System.out.println("猫不会游泳"); + } + } +} \ No newline at end of file diff --git a/w6/Cat.class b/w6/Cat.class new file mode 100644 index 0000000..ba40056 Binary files /dev/null and b/w6/Cat.class differ diff --git a/w6/Cat.java b/w6/Cat.java new file mode 100644 index 0000000..30c87e1 --- /dev/null +++ b/w6/Cat.java @@ -0,0 +1,8 @@ +// 猫类:仅继承动物抽象类,不实现游泳接口 +public class Cat extends Animal { + // 重写抽象方法:猫的叫声 + @Override + public void makeSound() { + System.out.println("喵喵喵~"); + } +} diff --git a/w6/Dog.java b/w6/Dog.java new file mode 100644 index 0000000..99aaf68 --- /dev/null +++ b/w6/Dog.java @@ -0,0 +1,14 @@ +// 狗类:继承动物抽象类,同时实现游泳接口 +public class Dog extends Animal implements Swimmable { + // 重写抽象方法:狗的叫声 + @Override + public void makeSound() { + System.out.println("汪汪汪!"); + } + + // 实现接口方法:狗会游泳 + @Override + public void swim() { + System.out.println("狗刨式游泳"); + } +} \ No newline at end of file diff --git a/w6/Swimmable.java b/w6/Swimmable.java new file mode 100644 index 0000000..fea4154 --- /dev/null +++ b/w6/Swimmable.java @@ -0,0 +1,5 @@ +// 接口:可游泳的,定义游泳能力 +public interface Swimmable { + // 接口方法:游泳,默认public abstract,可省略 + void swim(); +}