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.
49 lines
1.1 KiB
49 lines
1.1 KiB
// 游泳接口
|
|
interface Swimmable {
|
|
void swim();
|
|
}
|
|
|
|
// 抽象动物类
|
|
abstract class Animal {
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 狗:继承Animal + 实现游泳接口
|
|
class Dog extends Animal implements Swimmable {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("小狗汪汪汪叫");
|
|
}
|
|
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("小狗会游泳,正在游泳");
|
|
}
|
|
}
|
|
|
|
// 猫:只继承Animal,不实现游泳接口
|
|
class Cat extends Animal {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("小猫喵喵喵叫");
|
|
}
|
|
}
|
|
|
|
// 主类名改成Main!和文件名Main.java完全一致
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
// 多态测试:父类引用指向子类对象
|
|
Animal animal1 = new Dog();
|
|
Animal animal2 = new Cat();
|
|
|
|
// 多态调用叫声
|
|
animal1.makeSound();
|
|
animal2.makeSound();
|
|
|
|
// 向下转型调用游泳方法
|
|
if (animal1 instanceof Dog dog) {
|
|
dog.swim();
|
|
}
|
|
}
|
|
}
|
|
=
|