java方法重载2

来源:互联网 发布:mysql ocp认证 编辑:程序博客网 时间:2024/04/27 20:56

在本例中,Box() 构造函数需要三个自变量,这意味着定义的所有Box对象必须给Box() 构造函数传递三个参数。
例如,下面的语句在当前情况下是无效的:
Box ob = new Box();
因为Box( )要求有三个参数,因此如果不带参数的调用它则是一个错误。
这会引起一些重要的问题。如果你只想要一个盒子而不在乎 (或知道)它的原始的尺寸该怎么办?
或,如果你想用仅仅一个值来初始化一个立方体,而该值可以被用作它的所有的三个尺寸又该怎么办?
如果Box 类是像现在这样写的,与此类似的其他问题你都没有办法解决,因为你只能带三个参数而没有别的选择权。 幸好,解决这些问题的方案是相当容易的:重载Box 构造函数,使它能处理刚才描述的情况。
下面程序是Box 的一个改进版本,它就是运用对Box构造函数的重载来解决这些问题的:
/* Here,Box defines three constructors to initialize the dimensions of a box various ways. */
class Box {
    double width;
    double height;
    double depth;
    // constructor used when all dimensions specified
    Box(double w,double h,double d) {
        width = w; height = h; depth = d;
    }
    // constructor used when no dimensions specified
    Box() {
        width = -1; // use -1 to indicate
        height = -1; // an uninitialized
        depth = -1; //
        box
    }
    // constructor used when cube is created
   Box(double len) {
        width = height = depth = len;
   }/
   / /compute and return volume
   double volume() { 
     return width * height * depth;
   }
}
class OverloadCons {
      public static void main(String args[]) {
      // create boxes using the various constructors
      Box mybox1 = new Box(10,20,15);
      Box mybox2 = new Box();
      Box mycube = new Box(7);
      double vol;
      // get volume of first box 
      vol = mybox1.volume();
     System.out.println("Volume of mybox1 is " + vol);
      // get volume of second box
      vol = mybox2.volume();
     System.out.println("Volume of mybox2 is " + vol);
      // get volume of cube
      vol = mycube.volume();
     System.out.println("Volume of mycube is " + vol);
     }
 }
该程序产生的输出如下所示:
Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 在本例中,当new执行时,根据指定的自变量调用适当的构造函数。