Java基础篇:构造函数重载

97 阅读2分钟

除了重载正常的方法外,构造函数也能够重载。实际上,对于大多数你创建的现实的类,重载构造函数是很常见的,并不是什么例外。为了理解为什么会这样,让我们回想上一章中举过的Box类例子。下面是最新版本的Box类的例子:

class Box { 
 double width; 
 double height; 
 double depth; 
 // This is the constructor for Box. 
 Box(double w,double h,double d) { 
  width = w; 
  height = h; 
  depth = d; 
 } 
 // compute and return volume 
 double volume() { 
 return width * height * depth; 
 } 
}

在本例中,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(102015); 
 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执行时,根据指定的自变量调用适当的构造函数。