并把操作信息输出到控制台。
(2)利用反射机制编写一个程序,这个程序能指定调用类的某个方法及构
造方法,并把操作信息输出到控制台。
(3)对类进行动态实例化 Class.forName()
为某研究所编写一个通用程序,用来计算每一种交通工具运行 1000 公里所
需的时间,已知每种交通工具的参数都是 3 个浮点数 A、B、C 的表达式。现有
两种工具:Car 和 Plane,其中 Car 的速度运算公式为:A*B/C,Plane 的速度运
算公式为:A+B+C;需要编写三个类:ComputeTime、Plane、Car 和接口 Common,
要求在未来如果增加第 3 种交通工具的时候,不必修改以前的任何程序,只需要
编写新的交通工具的程序。
动态实例化代码:
Class.forName(args[0]).newInstance();
注意事项:
以下为代码:
public class Car implements Common {
private int speed;
public int calspeed(int a,int b,int c) {
return speed=a*b/c;
}
}
public class Plane implements Common {
private int speed;
public int calspeed(int a,int b,int c) {
return speed=a+b+c;
}
}
public interface Common {
public abstract int calspeed(int a,int b,int c);
}
public class ComputeTime {
public static void main(String args[]) throws Exception{
System.out.println("交通工具"+args[0]);
System.out.println("a"+args[1]);
System.out.println("b"+args[2]);
System.out.println("c"+args[3]);
int a=Integer.parseInt(args[1]);
int b=Integer.parseInt(args[2]);
int c=Integer.parseInt(args[3]);
int v,t;
Common d=(Common) Class.forName(args[0]).newInstance();
v=d.calspeed(a, b, c);
System.out.println("速度是"+v);
}
}
结果
交通工具Car
a3
b2
c3
速度是2