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.

56 lines
1.3 KiB

// 抽象类Animal
abstract class Animal {
// 抽象方法makesound()
public abstract void makesound();
}
// 接口Swimmable
interface Swimmable {
// 方法swim()
void swim();
}
// Dog类继承Animal并实现Swimmable接口
class Dog extends Animal implements Swimmable {
@Override
public void makesound() {
System.out.println("Dog barks: Woof! Woof!");
}
@Override
public void swim() {
System.out.println("Dog is swimming");
}
}
// Cat类继承Animal
class Cat extends Animal {
@Override
public void makesound() {
System.out.println("Cat meows: Meow! Meow!");
}
}
public class Animals {
public static void main(String[] args) {
// 多态测试
Animal animal1 = new Dog();
Animal animal2 = new Cat();
System.out.println("Testing polymorphism:");
animal1.makesound();
animal2.makesound();
// 测试Dog的swim方法
System.out.println("\nTesting swim method:");
if (animal1 instanceof Swimmable) {
((Swimmable) animal1).swim();
}
if (animal2 instanceof Swimmable) {
((Swimmable) animal2).swim();
} else {
System.out.println("Cat cannot swim");
}
}
}