diff --git a/Animal.class b/Animal.class new file mode 100644 index 0000000..4f66632 Binary files /dev/null and b/Animal.class differ diff --git a/AnimalTest.class b/AnimalTest.class new file mode 100644 index 0000000..2a3562e Binary files /dev/null and b/AnimalTest.class differ diff --git a/AnimalTest.java b/AnimalTest.java new file mode 100644 index 0000000..2cef587 --- /dev/null +++ b/AnimalTest.java @@ -0,0 +1,57 @@ +// 1. 抽象类 Animal +abstract class Animal { + // 抽象方法:动物叫 + public abstract void makeSound(); +} + +// 2. 接口 Swimmable +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("猫叫:喵喵喵 🐱"); + } +} + +// 5. 主类(必须public,和文件名一致) +public class AnimalTest { + public static void main(String[] args) { + // 多态:父类引用指向子类对象 + Animal dog = new Dog(); + Animal cat = new Cat(); + + // 调用叫声方法 + System.out.println("=== 动物叫声测试 ==="); + dog.makeSound(); + cat.makeSound(); + + // 测试游泳接口:只有Dog实现了Swimmable + System.out.println("\n=== 游泳能力测试 ==="); + if (dog instanceof Swimmable) { + ((Swimmable) dog).swim(); + } + if (cat instanceof Swimmable) { + ((Swimmable) cat).swim(); + } else { + System.out.println("猫不会游泳,只能在边上看着~"); + } + } +} \ No newline at end of file diff --git a/Cat.class b/Cat.class new file mode 100644 index 0000000..ea7e522 Binary files /dev/null and b/Cat.class differ diff --git a/Dog.class b/Dog.class new file mode 100644 index 0000000..4daf623 Binary files /dev/null and b/Dog.class differ