2 changed files with 57 additions and 0 deletions
@ -0,0 +1 @@ |
|||||
|
本次Java课堂练习中,我向AI提出了“按需求编写动物叫声系统代码”的请求,AI先帮我梳理了抽象类、接口、多态的核心逻辑,明确了Animal抽象类、Swimmable接口的设计思路,再一步步写出完整可运行的代码,标注了关键语法要点。同时AI补充了instanceof类型判断的规范写法,避免运行报错,还解释了多态调用的原理,帮我理清了抽象类和接口的区别,最后按要求调整了代码结构,确保完全符合课堂练习的需求。 |
||||
@ -0,0 +1,56 @@ |
|||||
|
// 抽象类 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("猫不会游泳"); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue