You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.4 KiB
56 lines
1.4 KiB
// 抽象类 Animal
|
|
abstract class Animal {
|
|
// 抽象方法:发出声音
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 接口 Swimmable
|
|
interface Swimmable {
|
|
// 游泳方法
|
|
void swim();
|
|
}
|
|
|
|
// Dog 类继承 Animal 并实现 Swimmable 接口
|
|
class Dog extends Animal implements Swimmable {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("汪汪汪");
|
|
}
|
|
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("小狗在游泳");
|
|
}
|
|
}
|
|
|
|
// Cat 类仅继承 Animal
|
|
class Cat extends Animal {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("喵喵喵");
|
|
}
|
|
}
|
|
|
|
// 测试类
|
|
public class AnimalSoundSystem {
|
|
public static void main(String[] args) {
|
|
// 多态调用:Animal 类型引用子类对象
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
System.out.println("=== 动物叫声测试 ===");
|
|
dog.makeSound();
|
|
cat.makeSound();
|
|
|
|
System.out.println("\n=== 游泳能力测试 ===");
|
|
// 向下转型:只有 Dog 实现了 Swimmable,才能调用 swim()
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
}
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println("猫不会游泳");
|
|
}
|
|
}
|
|
}
|