diff --git a/.gitignore b/.gitignore index 13275f1..89f64a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.idea/ + ### IntelliJ IDEA ### out/ !**/src/main/**/out/ diff --git a/src/w7/Main.java b/src/w7/Main.java new file mode 100644 index 0000000..77e3246 --- /dev/null +++ b/src/w7/Main.java @@ -0,0 +1,51 @@ +package w7; +// Animal.java - 动物抽象类 +abstract class Animal { + public abstract void makeSound(); // 抽象方法:发出声音 +} + +// Swimable.java - 游泳接口 +interface Swimable { + void swim(); // 游泳方法 +} + +// Dog.java - 狗类继承动物并实现游泳接口 +class Dog extends Animal implements Swimable { + @Override + public void makeSound() { + System.out.println("狗叫:汪汪!"); + } + + @Override + public void swim() { + System.out.println("狗在游泳。"); + } +} + +// Cat.java - 猫类只继承动物,不实现游泳接口 +class Cat extends Animal { + @Override + public void makeSound() { + System.out.println("猫叫:喵喵!"); + } +} + +// Main.java - 测试多态调用 +public class Main { + public static void main(String[] args) { + // 多态:父类引用指向子类对象 + Animal myDog = new Dog(); + Animal myCat = new Cat(); + + // 调用 makeSound() - 展示不同动物的不同行为 + myDog.makeSound(); // 狗叫 + myCat.makeSound(); // 猫叫 + + // 测试游泳:只有狗能游泳(使用 instanceof 检查类型) + if (myDog instanceof Swimable) { + ((Swimable) myDog).swim(); // 狗游泳 + } + + // 猫不能游泳(Cat 没有实现 Swimable 接口) + } +} \ No newline at end of file