如何使用Java创建一个名为Animal的接口,该接口包含一个run()方法?然后,请分别定义Bird和Fish类来实现这个接口,并为这两个类编写测试程序,在测试程序中调用各自的run()方法。具体步骤是什么?
时间: 2024-11-15 15:24:01 浏览: 31
首先,我们来创建一个名为`Animal`的接口,并定义其`run()`方法:
```java
// 创建Animal接口
public interface Animal {
void run();
}
```
接着,我们会定义两个类`Bird`和`Fish`,它们都会实现`Animal`接口并提供自己的`run()`方法:
```java
// Bird类实现Animal接口
public class Bird implements Animal {
@Override
public void run() {
System.out.println("鸟儿正在飞翔");
}
}
// Fish类也实现Animal接口
public class Fish implements Animal {
@Override
public void run() {
System.out.println("鱼儿正在水中游动");
}
}
```
现在,我们可以编写测试程序来演示如何调用这两个类的`run()`方法:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 随机选择一个动物实例
Random random = new Random();
int choice = random.nextInt(2); // 0为Bird, 1为Fish
Animal animal;
if (choice == 0) {
animal = new Bird(); // 创建Bird对象
} else {
animal = new Fish(); // 创建Fish对象
}
// 调用各自的run()方法
animal.run();
// 输出结果
System.out.println("当前动物:" + animal.getClass().getSimpleName());
}
}
```
在这个测试程序中,我们通过随机数选择`Bird`或`Fish`的一个实例,并调用它们的`run()`方法。运行这段程序会看到不同的动物行为。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)