java中 一些比较有特征的方法

有时候,重载和重写的方式有些复杂,在jdk5里面。有一些方式能简化一些。

我们来看看吧,jdk5的可变参数。 如果把相同参数类型的方法重载好几遍真的是很烦。

就一个方法,pri(String args), pri(String arg0 ,String arg1), pri(String arg0,String arg1,String arg2), pri(String arg0,String arg1,String arg2,String arg3)

这样的话会写很多烦琐的代码。现在jdk5可以,用“”来代替这些参数。

实践:

 public class overload {

//若干个相同类型的参数,用“...”代替

   public void pri(String... strings ){

       for (String str : strings)   //for这个循环语句也有迭代的意思

       System.out.print(str);

   }

   public static void main(String[] args){

       new overload().pri("100jq"," 百家拳软件项目研究室"," www.100jq.com");

   }

jdk5的方法重写,比以前多了一个叫做协变返回的概念。在以往jdk的版本中,还有一个比较让人讨厌的地方。方法重写确实是比较不错的机制,如果想用父类的方法,写个super就可以了,如果不想用父类的方法就重写覆盖。但是重写覆盖的返回类型不能覆盖,父类的类型不够用怎么办,我们想在子类重写它的类型可以吗?现在可以了。

看下面的例子:

class Point2D { //定义二维的点

  protected int x, y;

  public Point2D() {

    this.x=0;

    this.y=0;}

  public Point2D(int x, int y) {

    this.x = x;

    this.y = y;

  }}

//定义三维的点,继承二维

class Point3D extends Point2D {

  protected int z;

  public Point3D(int x, int y) {

    this(x, y, 0);

  }

  public Point3D(int x, int y, int z) {

    this.x = x;

    this.y = y;

    this.z = z;

  }}

//定义二维的位置

class Position2D {

  Point2D location;

  public Position2D() {

    this.location = new Point2D();

  }

  public Position2D(int x, int y) {

    this.location = new Point2D(x, y);

  }

  public Point2D getLocation() {

    return location;

  }}

//定义三维的位置,继承二维的位置

class Position3D extends Position2D {

  Point3D location; //在这里已经变成Point3D的类型了

  public Position3D(int x, int y, int z) {

    this.location = new Point3D(x, y, z);

  }

  @Override  //注释是重写方法

  public Point3D getLocation() {

    return location; //返回是子类的类型而不是原来的类型了

  }

posted @ 2011-05-24 11:35  Joly-Han  阅读(242)  评论(0编辑  收藏  举报