2、使用抽象类和接口两种方式实现下面的代码 1)、饲养员喂养动物 饲养员在给动物喂食时,给不同的动物喂不同的食物,而且在每次喂食时,动物都会发出欢快的叫声。例如,给小狗喂骨头,小狗会汪汪叫;给小猫喂食,小猫会喵喵叫。 本案例要求编写一个程序模拟饲养员喂食动物的过程,案例要求如下: (1)饲养员给小狗喂骨头,小狗汪汪叫。 (2)饲养员给小猫喂小鱼,小猫喵喵叫。
时间: 2023-05-26 16:05:57 浏览: 222
使用抽象类的实现方式:
```java
abstract class Animal {
protected String food;
public abstract void eat();
public void shout() {
System.out.println("叫声");
}
}
class Dog extends Animal {
public Dog(String food) {
this.food = food;
}
public void eat() {
System.out.println("给小狗喂食:" + food);
shout();
}
public void shout() {
System.out.println("小狗汪汪叫");
}
}
class Cat extends Animal {
public Cat(String food) {
this.food = food;
}
public void eat() {
System.out.println("给小猫喂食:" + food);
shout();
}
public void shout() {
System.out.println("小猫喵喵叫");
}
}
class Zookeeper {
public void feed(Animal animal) {
animal.eat();
}
}
public class Main {
public static void main(String[] args) {
Zookeeper zookeeper = new Zookeeper();
Animal dog = new Dog("骨头");
Animal cat = new Cat("小鱼");
zookeeper.feed(dog); // 饲养员给小狗喂骨头,小狗汪汪叫
zookeeper.feed(cat); // 饲养员给小猫喂小鱼,小猫喵喵叫
}
}
```
使用接口的实现方式:
```java
interface Animal {
void eat(String food);
void shout();
}
class Dog implements Animal {
public void eat(String food) {
System.out.println("给小狗喂食:" + food);
shout();
}
public void shout() {
System.out.println("小狗汪汪叫");
}
}
class Cat implements Animal {
public void eat(String food) {
System.out.println("给小猫喂食:" + food);
shout();
}
public void shout() {
System.out.println("小猫喵喵叫");
}
}
class Zookeeper {
public void feed(Animal animal, String food) {
animal.eat(food);
}
}
public class Main {
public static void main(String[] args) {
Zookeeper zookeeper = new Zookeeper();
Animal dog = new Dog();
Animal cat = new Cat();
zookeeper.feed(dog, "骨头"); // 饲养员给小狗喂骨头,小狗汪汪叫
zookeeper.feed(cat, "小鱼"); // 饲养员给小猫喂小鱼,小猫喵喵叫
}
}
```
阅读全文