1 changed files with 59 additions and 0 deletions
@ -0,0 +1,59 @@ |
|||
// 1. 抽象类 Animal(顶级类,不嵌套在Main里)
|
|||
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)
|
|||
class Cat extends Animal { |
|||
@Override |
|||
public void makeSound() { |
|||
System.out.println("猫叫:喵喵喵!"); |
|||
} |
|||
} |
|||
|
|||
// 5. 主类 Main(唯一public类,包含标准main方法)
|
|||
public class Main { |
|||
// ✅ 正确的main方法:public static + String[]参数
|
|||
public static void main(String[] args) { |
|||
// 测试多态调用
|
|||
System.out.println("=== 多态测试:动物叫声 ==="); |
|||
Animal dog = new Dog(); |
|||
Animal cat = new Cat(); |
|||
dog.makeSound(); |
|||
cat.makeSound(); |
|||
|
|||
System.out.println("\n=== 接口测试:游泳能力 ==="); |
|||
Swimmable swimmer = new Dog(); |
|||
swimmer.swim(); |
|||
|
|||
System.out.println("\n=== 综合遍历测试 ==="); |
|||
Animal[] animals = {new Dog(), new Cat()}; |
|||
for (Animal animal : animals) { |
|||
animal.makeSound(); |
|||
// 判断是否实现了Swimmable接口
|
|||
if (animal instanceof Swimmable) { |
|||
((Swimmable) animal).swim(); |
|||
} else { |
|||
System.out.println("该动物不会游泳"); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue