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.
48 lines
1.4 KiB
48 lines
1.4 KiB
// 游泳接口,包含抽象游泳方法
|
|
public interface Swimmable {
|
|
void swim();
|
|
}
|
|
// 抽象动物类,包含抽象叫声方法
|
|
public abstract class Animal {
|
|
// 抽象方法:动物发出叫声,子类必须重写实现
|
|
public abstract void makeSound();
|
|
}
|
|
public class Dog extends Animal implements Swimmable {
|
|
// 重写父类抽象叫声方法
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("小狗汪汪汪~");
|
|
}
|
|
|
|
// 实现接口的游泳方法
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("小狗会游泳,在水里欢快扑腾");
|
|
}
|
|
}
|
|
public class Cat extends Animal {
|
|
// 重写父类抽象叫声方法
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("小猫喵喵喵~");
|
|
}
|
|
}
|
|
public class TestAnimal {
|
|
public static void main(String[] args) {
|
|
// 父类引用指向子类对象,Java多态核心写法
|
|
Animal animal1 = new Dog();
|
|
Animal animal2 = new Cat();
|
|
|
|
// 多态调用:统一调用makeSound,自动执行对应子类重写方法
|
|
animal1.makeSound();
|
|
animal2.makeSound();
|
|
|
|
// 向下转型,调用Dog独有的游泳接口方法
|
|
if (animal1 instanceof Dog) {
|
|
Dog dog = (Dog) animal1;
|
|
dog.swim();
|
|
}
|
|
|
|
// 猫没有实现游泳接口,无法调用swim()方法
|
|
}
|
|
}
|
|
|