1.抽象类练习。
下面展示一些 内联代码片
。
public class Text {
public static void main(String[] args) {
yuan a=new yuan(3);
juxing b=new juxing(7,10);
System.out.println("圆面积="+a.getArea()+"圆周长="+b.getPerimeter());
System.out.println("矩形面积="+b.getArea()+"矩形周长="+b.getPerimeter());
}
}
abstract class Shapes{
public double witch,height;
public Shapes(double witch,double height) {
this.witch=witch;
this.height=height;
}
abstract double getArea();
abstract double getPerimeter();
}
class yuan extends Shapes{
private double r;
public yuan(double r) {
super(2*r,2*r);
this.r=r;
}
double getArea() {
return Math.PI*r*r;
}
double getPerimeter() {
return Math.PI*2*r;
}
}
class juxing extends Shapes{
public juxing(double w,double h) {
super(w, h);
}
double getArea() {
return witch*height;
}
double getPerimeter() {
return 2*witch+2*height;
}
}
2、为某研究所编写一个通用程序,用来计算每一种交通工具运行 1000公里所需的时间,已知每种交通工具的参数都是3个整数A、B、C的表达式。现有两种工具:Car 和Plane,其中Car 的速度运算公式为:A*B/C,Plane 的速度运算公式为:A+B+C。
( 1 )需要编写两个类: Plane.java,Car007.java和接口Common.java,在该接口中提供交通工具计算速度的抽象方法。要求在未来如果增加第3种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。
( 2 )其运行过程如下,从命令行输入测试类ComputeTime的四个参数,第一个是交通工具的类型,第二、三、四个参数分别时整数A、B、C,举例如下:计算Plane的时间:″java ComputeTime Plane 20 30 40″
计算Car007的时间:”java ComputeTime Car007 23 34 45″
如果第3种交通工具为Ship,则只需要编写Ship.java,运行时输入:”java ComputeTime Ship 22 33 44″
提示:充分利用接口的概念,接口对象充当参数。
( 3 )实例化一个对象的另外一种办法:Class.forName(str).newInstance();例如需要实例化一个Plane对象的话,则只要调用Class.forName(“Plane”).newInstance()便可,注意通过此方方法创建的对象类型为Object类型,所以必须做类型转换,转成Common类型。
下面展示一些 内联代码片
。
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]);
double A=Double.parseDouble(args[1]);
double B=Double.parseDouble(args[2]);
double C=Double.parseDouble(args[3]);
Common x=(Common)Class.forName(args[0]).newInstance();
double speed=x.speed(A, B, C);
System.out.println("该交通工具运行速度为:"+speed);
System.out.println("运行1000公里使用的时间为:"+1000/speed);
}
}
interface Common{
public double speed(double a,double b,double c);
}
class Car007 implements Common{
public double speed(double a,double b,double c) {
return a*b/c;
}
}
class Plane implements Common{
public double speed(double a,double b,double c) {
return a+b+c;
}
}
class Ship implements Common{
public double speed(double a,double b,double c) {
return (a+b)*c;
}
}