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
2.3 KiB
80 lines
2.3 KiB
/**
|
|
* 练习1:动物叫声系统
|
|
* 需求:使用抽象类和接口改进动物系统
|
|
* 1. 创建抽象类Animal,包含抽象方法makeSound()
|
|
* 2. 创建Dog和Cat继承Animal
|
|
* 3. 创建接口Swimmable,包含方法swim()
|
|
* 4. 让Dog实现Swimmable,Cat不实现
|
|
* 5. 在main方法中测试多态调用
|
|
*/
|
|
|
|
// 游泳接口:定义会游泳的动物的行为规范
|
|
interface Swimmable {
|
|
/**
|
|
* 游泳方法
|
|
*/
|
|
void swim();
|
|
}
|
|
|
|
// 抽象动物类:所有动物的父类,定义通用行为
|
|
abstract class Animal {
|
|
/**
|
|
* 抽象方法:发出声音,由具体子类实现
|
|
*/
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 狗类:继承Animal,实现Swimmable接口(会游泳)
|
|
class Dog extends Animal implements Swimmable {
|
|
/**
|
|
* 实现抽象方法:狗的叫声
|
|
*/
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("汪汪汪!");
|
|
}
|
|
|
|
/**
|
|
* 实现Swimmable接口:狗的游泳行为
|
|
*/
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("小狗在水里游泳~");
|
|
}
|
|
}
|
|
|
|
// 猫类:仅继承Animal,不实现Swimmable(不会游泳)
|
|
class Cat extends Animal {
|
|
/**
|
|
* 实现抽象方法:猫的叫声
|
|
*/
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("喵喵喵~");
|
|
}
|
|
}
|
|
|
|
// 主类:包含main方法,用于测试多态调用
|
|
public class AnimalSystem {
|
|
public static void main(String[] args) {
|
|
// 1. 多态创建动物数组:父类引用指向子类对象
|
|
Animal[] animals = {new Dog(), new Cat()};
|
|
|
|
// 2. 多态调用makeSound()方法,体现面向对象多态特性
|
|
System.out.println("===== 动物叫声测试 =====");
|
|
for (Animal animal : animals) {
|
|
animal.makeSound();
|
|
}
|
|
|
|
// 3. 测试游泳能力:只有实现Swimmable接口的Dog可以调用swim()
|
|
System.out.println("\n===== 游泳能力测试 =====");
|
|
for (Animal animal : animals) {
|
|
// 类型判断:安全转型,避免类型转换异常
|
|
if (animal instanceof Swimmable) {
|
|
((Swimmable) animal).swim();
|
|
} else {
|
|
System.out.println(animal.getClass().getSimpleName() + "不会游泳");
|
|
}
|
|
}
|
|
}
|
|
}
|