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.
66 lines
2.2 KiB
66 lines
2.2 KiB
// 1. 定义Swimmable接口:包含swim()方法
|
|
public interface Swimmable {
|
|
// 接口方法默认public abstract,可省略修饰符
|
|
void swim();
|
|
}
|
|
|
|
// 2. 定义抽象类Animal:包含抽象方法makeSound()
|
|
public abstract class Animal {
|
|
// 抽象方法:没有方法体,由子类实现
|
|
public abstract void makeSound();
|
|
}
|
|
|
|
// 3. Dog类:继承Animal,实现Swimmable接口
|
|
public class Dog extends Animal implements Swimmable {
|
|
// 实现父类抽象方法makeSound()
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("狗叫:汪汪汪!");
|
|
}
|
|
|
|
// 实现Swimmable接口的swim()方法
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("狗在游泳:狗刨式!");
|
|
}
|
|
}
|
|
|
|
// 4. Cat类:仅继承Animal,不实现Swimmable接口
|
|
public class Cat extends Animal {
|
|
// 实现父类抽象方法makeSound()
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("猫叫:喵喵喵!");
|
|
}
|
|
}
|
|
|
|
// 5. 主类:测试多态调用
|
|
public class AnimalTest {
|
|
public static void main(String[] args) {
|
|
// 多态1:父类引用指向子类对象(Animal多态)
|
|
Animal dog1 = new Dog();
|
|
Animal cat1 = new Cat();
|
|
|
|
System.out.println("=== Animal多态调用makeSound() ===");
|
|
dog1.makeSound(); // 调用Dog类的makeSound()
|
|
cat1.makeSound(); // 调用Cat类的makeSound()
|
|
|
|
// 多态2:接口引用指向实现类对象(Swimmable多态)
|
|
Swimmable dog2 = new Dog();
|
|
System.out.println("\n=== Swimmable多态调用swim() ===");
|
|
dog2.swim(); // 调用Dog类的swim()
|
|
|
|
// 类型转换:将Animal类型的dog1转为Swimmable,调用swim()
|
|
System.out.println("\n=== 类型转换后调用swim() ===");
|
|
if (dog1 instanceof Swimmable) { // 安全判断:避免类型转换异常
|
|
Swimmable swimmableDog = (Swimmable) dog1;
|
|
swimmableDog.swim();
|
|
}
|
|
|
|
// Cat无法转换为Swimmable,会抛出异常,因此不执行
|
|
// if (cat1 instanceof Swimmable) {
|
|
// Swimmable swimmableCat = (Swimmable) cat1;
|
|
// swimmableCat.swim();
|
|
// }
|
|
}
|
|
}
|