定义Bird类和Fish类实现Animal接口编写程序
时间: 2024-01-14 19:05:10 浏览: 67
好的,下面是Bird类和Fish类的定义,并且它们都实现了Animal接口的要求。
```java
// Animal接口
interface Animal {
void eat();
void sleep();
}
// Bird类实现Animal接口
class Bird implements Animal {
@Override
public void eat() {
System.out.println("Bird is eating.");
}
@Override
public void sleep() {
System.out.println("Bird is sleeping.");
}
public void fly() {
System.out.println("Bird is flying.");
}
}
// Fish类实现Animal接口
class Fish implements Animal {
@Override
public void eat() {
System.out.println("Fish is eating.");
}
@Override
public void sleep() {
System.out.println("Fish is sleeping.");
}
public void swim() {
System.out.println("Fish is swimming.");
}
}
// 测试程序
public class Main {
public static void main(String[] args) {
Bird bird = new Bird();
bird.eat();
bird.sleep();
bird.fly();
Fish fish = new Fish();
fish.eat();
fish.sleep();
fish.swim();
}
}
```
这段代码定义了一个Animal接口,以及Bird类和Fish类分别实现了该接口。在测试程序中,我们创建了一个Bird对象和一个Fish对象,并调用它们的eat()、sleep()方法,以及Bird特有的fly()方法和Fish特有的swim()方法。
阅读全文