3、通过菜单选择动物,输出动物爱吃什么,要求: 1)定义接口IAnimal,在接口中定义eat()方法; 2)定义类Dog,实现接口IAnimal; 3)定义类Cat,实现接口IAnimal; 4)提供Test类进行测试。
时间: 2024-03-10 07:47:03 浏览: 19
好的,我明白了您的问题。以下是代码实现:
```java
// 定义接口IAnimal
interface IAnimal {
void eat();
}
// 定义类Dog,实现接口IAnimal
class Dog implements IAnimal {
@Override
public void eat() {
System.out.println("Dog likes to eat meat.");
}
}
// 定义类Cat,实现接口IAnimal
class Cat implements IAnimal {
@Override
public void eat() {
System.out.println("Cat likes to eat fish.");
}
}
// 提供Test类进行测试
public class Test {
public static void main(String[] args) {
// 通过菜单选择动物
IAnimal animal = null;
String choice = "dog"; // 假设选择了狗
if (choice.equals("dog")) {
animal = new Dog();
} else if (choice.equals("cat")) {
animal = new Cat();
}
// 输出动物爱吃什么
animal.eat();
}
}
```
在这个例子中,我们定义了一个接口 `IAnimal`,它有一个 `eat()` 方法。然后我们定义了两个类 `Dog` 和 `Cat`,它们都实现了这个接口,并且分别实现了它们自己的 `eat()` 方法。
最后,我们提供了一个 `Test` 类进行测试。在这个类中,我们通过菜单选择了一个动物,然后调用它的 `eat()` 方法,输出它爱吃什么。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)