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.0 KiB
48 lines
1.0 KiB
Animal.java:
|
|
public abstract class Animal {
|
|
public abstract void makeSound();
|
|
}
|
|
Dog.java:
|
|
public class Dog extends Animal implements Swimmable {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("汪汪汪!");
|
|
}
|
|
|
|
@Override
|
|
public void swim() {
|
|
System.out.println("狗在游泳!");
|
|
}
|
|
}
|
|
Cat.java:
|
|
public class Cat extends Animal {
|
|
@Override
|
|
public void makeSound() {
|
|
System.out.println("喵喵喵!");
|
|
}
|
|
}
|
|
Main.java:
|
|
public class Main {
|
|
public static void main(String[] args) {
|
|
// 多态调用
|
|
Animal dog = new Dog();
|
|
Animal cat = new Cat();
|
|
|
|
System.out.println("狗的叫声:");
|
|
dog.makeSound();
|
|
|
|
System.out.println("猫的叫声:");
|
|
cat.makeSound();
|
|
|
|
// 测试游泳功能
|
|
if (dog instanceof Swimmable) {
|
|
((Swimmable) dog).swim();
|
|
}
|
|
|
|
if (cat instanceof Swimmable) {
|
|
((Swimmable) cat).swim();
|
|
} else {
|
|
System.out.println("猫不会游泳!");
|
|
}
|
|
}
|
|
}
|