1.定义动物类 属性:年龄行为:喝水,吃东西【吃什么不确定】 2.定义游泳接口: 行为:游泳方法 3.定义狗类 行为:吃饭(啃骨头)和 游泳(狗刨) 4.定义羊类: 行为:吃饭(羊啃草) 5.定义青蛙类: 行为:吃饭(吃虫子)和 游泳(蛙泳) 6.定义饲养员类: 行为:饲养动物:包括吃饭和喝水 7.定义测试类: 创建饲养员对象,饲养员调用三次饲养方法:饲养狗,饲养羊,饲养青蛙
时间: 2024-01-07 08:03:28 浏览: 122
好的,以下是符合您要求的代码:
```java
// 定义动物类
abstract class Animal {
private int age;
public Animal(int age) {
this.age = age;
}
public void drinkWater() {
System.out.println("Animal drinks water.");
}
public abstract void eat();
}
// 定义游泳接口
interface Swimable {
void swim();
}
// 定义狗类
class Dog extends Animal implements Swimable {
public Dog(int age) {
super(age);
}
public void eat() {
System.out.println("Dog eats bone.");
}
public void swim() {
System.out.println("Dog swims with dog paddle.");
}
}
// 定义羊类
class Sheep extends Animal {
public Sheep(int age) {
super(age);
}
public void eat() {
System.out.println("Sheep eats grass.");
}
}
// 定义青蛙类
class Frog extends Animal implements Swimable {
public Frog(int age) {
super(age);
}
public void eat() {
System.out.println("Frog eats insects.");
}
public void swim() {
System.out.println("Frog swims with frog kick.");
}
}
// 定义饲养员类
class Keeper {
public void feed(Animal animal) {
animal.drinkWater();
animal.eat();
}
}
// 定义测试类
public class Test {
public static void main(String[] args) {
Keeper keeper = new Keeper();
Dog dog = new Dog(2);
Sheep sheep = new Sheep(3);
Frog frog = new Frog(1);
keeper.feed(dog);
dog.swim();
keeper.feed(sheep);
keeper.feed(frog);
frog.swim();
}
}
```
运行结果如下:
```
Animal drinks water.
Dog eats bone.
Dog swims with dog paddle.
Animal drinks water.
Sheep eats grass.
Animal drinks water.
Frog eats insects.
Frog swims with frog kick.
```
阅读全文