题目二 交通工具通用程序:为某研究所编写一个通用程序,用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数A、B、C的表达式。现有两种工具:Car007 和Plane,其中Car007 的速度运算公式为:A*B/C,Plane 的速度运算公式为:A+B+C。需要编写三个类:ComputeTime.java,Plane.java,Car007.java和接口Common.java,要求在未来如果增加第3种或多种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程
时间: 2024-02-03 07:12:29 浏览: 96
序并实现Common接口即可。
首先,我们来定义Common接口:
```java
public interface Common {
public int computeTime(int distance);
}
```
该接口包含一个computeTime方法,用于计算运行指定距离所需的时间。
接下来,我们来实现ComputeTime类:
```java
public class ComputeTime {
public static void main(String[] args) {
int distance = 1000;
Common car = new Car007(60, 300, 20);
Common plane = new Plane(500, 200, 100);
System.out.println("Car007 needs " + car.computeTime(distance) + " hours to run " + distance + " km.");
System.out.println("Plane needs " + plane.computeTime(distance) + " hours to fly " + distance + " km.");
}
}
```
在main方法中,我们定义了要运行的距离为1000公里,并创建了Car007和Plane两个对象,分别使用了它们的参数进行初始化。
然后,我们调用了它们的computeTime方法,并输出了结果。
接下来,我们来实现Plane类:
```java
public class Plane implements Common {
private int a;
private int b;
private int c;
public Plane(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int computeTime(int distance) {
return distance / (a + b + c);
}
}
```
Plane类实现了Common接口,并定义了它自己的计算时间的方式。在构造函数中,我们使用a、b、c参数进行初始化。在computeTime方法中,我们根据Plane的速度公式计算所需时间,并返回结果。
最后,我们来实现Car007类:
```java
public class Car007 implements Common {
private int a;
private int b;
private int c;
public Car007(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int computeTime(int distance) {
return distance / (a * b / c);
}
}
```
Car007类同样实现了Common接口,并定义了它自己的计算时间的方式。在构造函数中,我们使用a、b、c参数进行初始化。在computeTime方法中,我们根据Car007的速度公式计算所需时间,并返回结果。
现在,我们可以运行ComputeTime类来计算Car007和Plane运行1000公里所需的时间了。如果以后要增加第3种或多种交通工具,只需要编写新的交通工具的类并实现Common接口即可,不需要修改以前的任何程序。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)