Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6644
  • 博文数量: 9
  • 博客积分: 230
  • 博客等级: 二等列兵
  • 技术积分: 100
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-08 14:32
文章分类
文章存档

2011年(9)

我的朋友
最近访客

分类: IT业界

2011-10-19 14:59:00

1、多态接口动态加载实例
  用来计算每一种交通工具运行1000公里所需的时间,已知每种交通工具的参数都是3个整数A、B、C的表达式。现有两种工具:粤嵌教育

  Car 和Plane,其中Car 的速度运算公式为:A*B/C
  Plane 的速度运算公式为:A+B+C。
  需要编写三类:ComputeTime.
,Plane.,Car007.和接口Common.,要求在未来如果增加第3种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。其运行过程如下,从命令行输入ComputeTime的四个参数,第一个是交通工具的类型,第二、三、四个参数分别时整数A、B、C,举例如下:
  计算Plane的时间:"
 ComputeTime Plane 20 30 40"
  计算Car007的时间:"
 ComputeTime Car007 23 34 45"粤嵌教育
  如果第3种交通工具为Ship,则只需要编写Ship.,运行时输入:" ComputeTime Ship 22 33 44"
  提示:充分利用接口的概念,接口对象充当参数。
  实例化一个对象的另外一种办法:Class.forName(str).newInstance();例如需要实例化一个Plane对象的话,则只要调用Class.forName("Plane").newInstance()便可。粤嵌教育

  Java代码
  import CalTime.vehicle.all.Common;
  import 
.lang.*;
  public interface Common ...{
  double runTimer(double a, double b, double c);
  }
  public class Plane implements Common  ...{
  public double runTimer(double a, double b, double c)  ...{
  return (a+ b + c);
  }
  }
  public class Car implements Common ...{
  public double runTimer(double a, double b, double c) ...{
  return ( a*b/c );
  }
  }
  public class ComputeTime ...{
  public static void main(String args[])  ...{
  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]);
  double v,t;
  try  ...{
  Common d=(Common) Class.forName("CalTime.vehicle."+args[0]).newInstance();
  v=d.runTimer(A,B,C);
  t=1000/v;
  System.out.println("平均速度: "+v+" km/h");
  System.out.println("运行时间:"+t+" 小时");
  }  catch(Exception e)    ...{
  System.out.println("class not found");
  }
  }
  }  以前看过一个求形状的题目就是有两个圆形求交集现在定义了两种情况问要是扩展大别的情况应当怎么设计,想了很久不得其解,现在忽然觉得接口通杀矣~


  2、接口作为参数传递
  可以将借口类型的参数作为方法参数,在实际是使用时可以将实现了接口的类传递给方法,后方法或按照重写的原则执行,实际调用的是实现类中的方法代码体,这样便根据传进屋的参数的不同而实现不同的功能。重要的是,当我以后徐要林外一个对象并且拥有接受说生命的方法的时候的时候,我们不必须原类,只需新的类实现借口即可。粤嵌教育
  Java代码
  import .lang.*;
  interface Extendbroadable ...{
  public void inPut();
  }
  class KeyBroad implements Extendbroadable ...{
  public void inPut() ...{
  System.out.println("  hi,keybroad has be input into then mainbroad! ");
  }
  }
  class NetCardBroad implements Extendbroadable ...{
  public void inPut() ...{
  System.out.println("  hi,netCardBroad has be input into then mainbroad! ");
  }
  }
  class CheckBroad ...{
  public void getMainMessage(Extendbroadable ext)...{
  ext.inPut();
  }
  }
  public class InterfaceTest01 ...{
  public static void main(String []args) ...{
  KeyBroad kb=new KeyBroad();
  NetCardBroad ncb=new NetCardBroad();
  CheckBroad cb=new CheckBroad();
  cb.getMainMessage(kb);
  cb.getMainMessage(ncb);
  }
  }

粤嵌教育

阅读(480) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~