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.
80 lines
1.9 KiB
80 lines
1.9 KiB
// 抽象类 Animal
|
|
abstract class Animal {
|
|
protected String name;
|
|
|
|
public Animal(String name) {
|
|
this.name = name;
|
|
}
|
|
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 接口 Swimmable
|
|
interface Swimmable {
|
|
void swim();
|
|
}
|
|
|
|
// Dog 类:继承 Animal,实现 Swimmable
|
|
class Dog extends Animal implements Swimmable {
|
|
public Dog(String name) {
|
|
super(name);
|
|
}
|
|
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println(name + " 汪汪叫");
|
|
}
|
|
|
|
@Override
|
|
public void swim() {
|
|
System.out.println(name + " 正在游泳 ");
|
|
}
|
|
}
|
|
|
|
// Cat 类:只继承 Animal,不实现 Swimmable
|
|
class Cat extends Animal {
|
|
public Cat(String name) {
|
|
super(name);
|
|
}
|
|
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println(name + " 喵喵叫");
|
|
}
|
|
}
|
|
|
|
// 测试主类
|
|
public class AnimalTest {
|
|
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=== 游泳测试 ===");
|
|
// 只有实现 Swimmable 的动物才能游泳
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
}
|
|
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println(cat.name + " 不会游泳 ");
|
|
}
|
|
|
|
System.out.println("\n=== 集合多态测试 ===");
|
|
// 将所有动物放入数组
|
|
Animal[] animals = {dog, cat};
|
|
for (Animal animal : animals) {
|
|
animal.makeSound();
|
|
// 检查是否会游泳
|
|
if (animal instanceof Swimmable) {
|
|
((Swimmable) animal).swim();
|
|
}
|
|
}
|
|
}
|
|
}
|