java饲养员投喂动物
时间: 2023-12-20 08:32:36 浏览: 154
饲养员
5星 · 资源好评率100%
以下是Java中饲养员投喂动物的示例代码:
```java
public class Feeder {
private String name;
public void feed(Animal animal) {
System.out.println(this.name + "喂" + animal.getName());
animal.eat();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public abstract class Animal {
private String name;
public abstract void eat();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃食物");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃食物");
}
}
```
使用示例:
```java
Feeder feeder = new Feeder();
feeder.setName("张三");
Cat cat = new Cat();
cat.setName("小猫");
Dog dog = new Dog();
dog.setName("小狗");
feeder.feed(cat); // 输出:张三喂小猫,猫吃食物
feeder.feed(dog); // 输出:张三喂小狗,狗吃食物
```
阅读全文