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.
 
 

66 lines
1.9 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,不实现 Swimmable
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("猫叫:喵喵喵~");
}
}
// 测试主类
public class AnimalSystem {
public static void main(String[] args) {
// 多态调用:父类引用指向子类对象
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();
}
// Cat 没有实现 Swimmable,不能调用 swim()
if (cat instanceof Swimmable) {
((Swimmable) cat).swim();
} else {
System.out.println("猫不会游泳,所以不能调用 swim() 方法");
}
System.out.println("\n===== 完整多态演示 =====");
// 使用 Swimmable 接口类型引用 Dog 对象
Swimmable swimmableDog = new Dog();
swimmableDog.swim();
// 验证 Dog 和 Cat 的类型
System.out.println("\ndog 是 Dog 的实例?" + (dog instanceof Dog));
System.out.println("dog 是 Swimmable 的实例?" + (dog instanceof Swimmable));
System.out.println("cat 是 Swimmable 的实例?" + (cat instanceof Swimmable));
}
}