为某研究所编写一个通用程序,用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数A、B、C的表达式。现有两种工具:Car 007 和Plane,其中Car 007 的速度运算公式为:A*B/C,Plane 的速度运算公式为:A+B+C。需要编写三类:Com p u t e Time.java, Plane.java, Car 007.java和接口Common.java,要求在未来如果增加第3种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。其运行过程如下,从命令行输入Compute Time的四个参数,第一个是交通工具的类型,第二、三、四个参数分别时整数A、B、C,举例如下:
计算Plane的时间:“java Compute Time Plane 20 30 40”
计算Car 007的时间:“java Compute Time Car 007 23 34 45”
如果第3种交通工具为Ship, 则只需要编写Ship.java,运行时输入:“java Compute Time Ship 22 33 44”
提示:充分利用接口的概念,接口对象充当参数。
实例化一个对象的另外一种办法:Class .for Name(s tr).new Instance();例如需要实例化一个Plane对象的话,则只要调用Class .for Name(“Plane”).new Instance()便可
Computer Time.java 源程序:
import pkg 1 .pkg 2.*;
import java.lang.*;
public class Computer Time
{ public static void main(String args[])
{ System .out .print l n("交通工具: "+args[0]);
System.out .print l n(" 参数A: "+args[1]);
System.out.print l n(" 参数B: "+args[2]);
System.out.print l n(" 参数C: "+args[3]);
double A=Double.parse Double(args[1]);
double B=Double.parse Double(args[2]);
double C=Double.parse Double(args[3]);
double v,t;
try { Common d=(Common) Class.for Name(“pkg 1.”+args[0]).new Instance();
v=d .run timer (A,B,C);
t=1000/v;
System .out.print l n(“平均速度: “+v+” km/h”);
System.out.print l n(“运行时间:”+t+" 小时");
}
catch(Exception e)
{ System.out.print l n(“class not found”);
}
}
}
包pkg 1中Car 007.java的源程序:
package pkg 1;
import pkg 1.pkg 2.*;
public class Car 007 implements Common
{ public double run timer(double A,double B,double C)
{ System.out.print l n(“runtime=”+(A*B/C));
return A*B/C;
}
}
包pkg 1中Plane.java的源程序:
package pkg 1;
import pkg 1.pkg 2.*;
public class Plane implements Common
{
public double run timer(double A,double B,double C)
{
return A+B+C;
}
}
包pkg 2中Common.java的源程序:
package pkg 1.pkg 2;
public interface Common
{
double run timer(double A,double B,double C);
}
}