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.
57 lines
1.5 KiB
57 lines
1.5 KiB
// 1. 抽象类 Animal
|
|
abstract class Animal {
|
|
// 抽象方法:动物叫
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 2. 接口 Swimmable
|
|
interface Swimmable {
|
|
// 游泳方法
|
|
void swim();
|
|
}
|
|
|
|
// 3. Dog 类:继承Animal,实现Swimmable接口
|
|
class Dog extends Animal implements Swimmable {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("狗叫:汪汪汪 🐶");
|
|
}
|
|
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("狗会游泳,正在刨水🏊♂️");
|
|
}
|
|
}
|
|
|
|
// 4. Cat 类:只继承Animal,不实现Swimmable
|
|
class Cat extends Animal {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("猫叫:喵喵喵 🐱");
|
|
}
|
|
}
|
|
|
|
// 5. 主类(必须public,和文件名一致)
|
|
public class AnimalTest {
|
|
public static void main(String[] args) {
|
|
// 多态:父类引用指向子类对象
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
// 调用叫声方法
|
|
System.out.println("=== 动物叫声测试 ===");
|
|
dog.makeSound();
|
|
cat.makeSound();
|
|
|
|
// 测试游泳接口:只有Dog实现了Swimmable
|
|
System.out.println("\n=== 游泳能力测试 ===");
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
}
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println("猫不会游泳,只能在边上看着~");
|
|
}
|
|
}
|
|
}
|