通过菜单选择动物,输出动物爱吃什么,要求: 1)定义接口IAnimal,在接口中定义eat()方法; 2)定义类Dog,实现接口IAnimal; 3)定义类Cat,实现接口IAnimal; 4)提供Test类进行测试。
时间: 2024-03-08 14:51:12 浏览: 27
好的,您的问题是如何通过菜单选择动物,输出动物爱吃什么,我来为您解答。
首先,我们需要按照要求定义接口IAnimal,代码如下:
```java
public interface IAnimal {
void eat();
}
```
接下来,我们定义类Dog和Cat,实现接口IAnimal,分别输出狗和猫爱吃的东西,代码如下:
```java
public class Dog implements IAnimal {
@Override
public void eat() {
System.out.println("Dog likes to eat bones.");
}
}
public class Cat implements IAnimal {
@Override
public void eat() {
System.out.println("Cat likes to eat fish.");
}
}
```
最后,我们提供Test类进行测试,代码如下:
```java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please choose the animal (1 for dog, 2 for cat): ");
int choice = scanner.nextInt();
IAnimal animal = null;
switch (choice) {
case 1:
animal = new Dog();
break;
case 2:
animal = new Cat();
break;
default:
System.out.println("Invalid choice.");
return;
}
animal.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)