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.
 
 

79 lines
2.4 KiB

//定义抽象类 Animal
abstract class Animal {
// 抽象方法:没有方法体,子类必须实现
public abstract void makeSound();
}
//定义接口 Swimmable
interface Swimmable {
// 接口中的方法默认是 public abstract
void swim();
}
// Dog 类继承 Animal,并实现 Swimmable
class Dog extends Animal implements Swimmable {
// 实现抽象方法 makeSound()
@Override
public void makeSound() {
System.out.println("汪汪汪!");
}
// 实现接口中的 swim() 方法
@Override
public void swim() {
System.out.println("狗会游泳,正在狗刨...");
}
}
// Cat 类只继承 Animal,不实现 Swimmable
class Cat extends Animal {
// 实现抽象方法 makeSound()
@Override
public void makeSound() {
System.out.println("喵喵喵~");
}
}
// 主类(测试类)
public class AnimalTest {
public static void main(String[] args) {
System.out.println("=== 动物叫声系统 ===\n");
// 多态:父类引用指向子类对象
Animal animal1 = new Dog();
Animal animal2 = new Cat();
// 调用 makeSound() - 表现出不同的行为
System.out.println("狗的声音:");
animal1.makeSound(); // 输出:汪汪汪!
System.out.println("\n猫的声音:");
animal2.makeSound(); // 输出:喵喵喵~
// 测试游泳能力(需要向下转型)
System.out.println("\n=== 游泳测试 ===");
// Dog 实现了 Swimmable,可以游泳
if (animal1 instanceof Swimmable) {
Swimmable swimmer = (Swimmable) animal1; // 向下转型
swimmer.swim(); // 输出:狗会游泳,正在狗刨...
}
// Cat 没有实现 Swimmable,不能游泳
if (animal2 instanceof Swimmable) {
System.out.println("猫会游泳"); // 不会执行
} else {
System.out.println("猫不会游泳"); // 输出:猫不会游泳
}
// 演示直接使用子类引用
System.out.println("\n=== 直接调用 ===");
Dog dog = new Dog();
dog.makeSound(); // 汪汪汪!
dog.swim(); // 狗会游泳,正在狗刨...
Cat cat = new Cat();
cat.makeSound(); // 喵喵喵~
// cat.swim(); // 编译错误!Cat没有swim方法
}
}