为某研究所编写一个通用程序,用来计算每一种交通工具运行 1000公里所需的时间.已知每种交通工具的参数都是3个整数常量A、B、C的表达式。
现有两种工具:Car 和Plane,
其中Car 的速度运算公式为:A*B/C,
Plane 的速度运算公式为 :A+B+C。
要求在未来如果增加第3种交通工具(如Ship)的时候,可以做到复用已有代码。
Ship的速度运算公式为 :A+B/C。
这里复用已有代码的意思是,比如专门定义了一个方法,用来计算所有交通工具的,移动指定距离所用的时间 , 可以不改变这个方法,继续用它计算新增加的交通工具的运行时间
double calculateTime(int distance, 计算对象) {
return 计算结果
}
要求自己设计该系统,并测试。
package com.company;
/**
* @Author:gaoyuan
* @Description:
* @DateTime:2021/1/11 20:51
**/
public class Test {
public static void main(String[] args) {
Vehicle car = new Car(5,6,7);
System.out.println("Car运行 1000公里所需的时间为:"+car.calculateTime(1000));
Plane plane = new Plane(5,6,7);
System.out.println("Plane运行 1000公里所需的时间为:"+plane.calculateTime(1000));
Ship ship = new Ship(5,6,7);
System.out.println("Ship运行 1000公里所需的时间为:"+ship.calculateTime(1000));
}
}
interface ComputationTime{
double calculateTime(int distance);//计算某种交通工具,移动指定距离例所花的时间
}
/**
* 该类抽象所有,类型交通工具的共性,3个参数a, b, c,
* 同时,所有交通工具都需要计算所需的时间,该计算方法放在了ComputationTime接口中
*/
abstract class Vehicle implements ComputationTime{
private int A;
private int B;
private int C;
public Vehicle(int a, int b, int c) {
A = a;
B = b;
C = c;
}
public abstract double getSpeed();
@Override
public double calculateTime(int distance){
return distance/getSpeed();
}
public int getA() {
return A;
}
public int getB() {
return B;
}
public int getC() {
return C;
}
}
class Car extends Vehicle{
public Car(int a, int b, int c) {
super(a, b, c);
}
@Override
public double getSpeed(){
return getA()*getB()/getC();
}
}
class Plane extends Vehicle {
public Plane(int a, int b, int c) {
super(a, b, c);
}
@Override
public double getSpeed(){
return getA()+getB()+getC();
}
}
class Ship extends Vehicle {
public Ship(int a, int b, int c) {
super(a, b, c);
}
@Override
public double getSpeed(){
return getA()+getB()/getC();
}
}