2、使用抽象类和接口两种方式实现下面的代码 饲养员在给动物喂食时,给不同的动物喂不同的食物,而且在每次喂食时,动物都会发出欢快的叫声。例如,给小狗喂骨头,小狗会汪汪叫;给小猫喂食,小猫会喵喵叫。 本案例要求编写一个程序模拟饲养员喂食动物的过程,案例要求如下: (1)饲养员给小狗喂骨头,小狗汪汪叫。 (2)饲养员给小猫喂小鱼,小猫喵喵叫。
时间: 2023-05-26 11:06:06 浏览: 179
使用抽象类实现:
```
abstract class Animal {
abstract void eat(String food);
void makeSound() {
System.out.println("Animal is making a sound...");
}
}
class Dog extends Animal {
void eat(String food) {
if (food.equals("bone")) {
System.out.println("Dog is eating " + food);
makeSound();
} else {
System.out.println("Dog does not eat " + food);
}
}
void makeSound() {
System.out.println("Dog is barking: " + "汪汪");
}
}
class Cat extends Animal {
void eat(String food) {
if (food.equals("fish")) {
System.out.println("Cat is eating " + food);
makeSound();
} else {
System.out.println("Cat does not eat " + food);
}
}
void makeSound() {
System.out.println("Cat is meowing: " + "喵喵");
}
}
public class Zoo {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat("bone");
Animal cat = new Cat();
cat.eat("fish");
}
}
```
使用接口实现:
```
interface Animal {
void eat(String food);
void makeSound();
}
class Dog implements Animal {
public void eat(String food) {
if (food.equals("bone")) {
System.out.println("Dog is eating " + food);
makeSound();
} else {
System.out.println("Dog does not eat " + food);
}
}
public void makeSound() {
System.out.println("Dog is barking: " + "汪汪");
}
}
class Cat implements Animal {
public void eat(String food) {
if (food.equals("fish")) {
System.out.println("Cat is eating " + food);
makeSound();
} else {
System.out.println("Cat does not eat " + food);
}
}
public void makeSound() {
System.out.println("Cat is meowing: " + "喵喵");
}
}
public class Zoo {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat("bone");
Animal cat = new Cat();
cat.eat("fish");
}
}
```
阅读全文