用Java实现为某研究所编写一个通用程序,用来计算每一种交通工具运行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:14:52 浏览: 149
程如下:
1. Common.java
```
public interface Common {
double computeTime(int distance);
}
```
2. ComputeTime.java
```
public class ComputeTime {
public static void main(String[] args) {
int distance = 1000;
Car007 car = new Car007(60, 5, 2);
Plane plane = new Plane(300, 200, 100);
double carTime = car.computeTime(distance);
double planeTime = plane.computeTime(distance);
System.out.println("Car007: " + carTime + " hours");
System.out.println("Plane: " + planeTime + " hours");
}
}
```
3. 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 double computeTime(int distance) {
double speed = A * B / (double) C;
return distance / speed;
}
}
```
4. 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 double computeTime(int distance) {
double speed = A + B + C;
return distance / speed;
}
}
```
如果需要增加第3种或多种交通工具,只需要编写一个实现了Common接口的类即可,不需要修改以前的任何程序。
阅读全文