Java基础篇:带自变量的构造函数

82 阅读1分钟

虽然Box构造函数确实初始化了Box对象,但它不是很有用,因为所有的盒子都是一样的尺寸。我们所需要的是一种能够构造各种各样尺寸盒子对象的方法。 比较容易的解决办法是对构造函数增加自变量。你可能已经猜到,这将使他们更有用。例如,下面版本的Box程序定义了一个自变量构造函数,它根据自变量设置每个指定盒子的尺寸。特别注意Box对象是如何被创建的。

/* Here,Box uses a parameterized constructor to 
 initialize the dimensions of a 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; 
 } 
} 
class BoxDemo7 { 
 public static void main(String args[]) { 
// declare,allocate,and initialize Box objects 
Box mybox1 = new Box(102015); 
Box mybox2 = new Box(369); 
double vol; 
// get volume of first box 
vol = mybox1.volume(); 
System.out.println("Volume is " + vol); 
// get volume of second box 
vol = mybox2.volume(); 
System.out.println("Volume is " + vol); 
 } 
}

该程序的输出如下:

Volume is 3000.0 
Volume is 162.0

正如你看到的,每个对象被它的构造函数指定的参数初始化。例如,在下行中,

Box mybox1 = new Box(102015); 

当new创建对象时,值10,20,15传递到Box()构造函数。这样,mybox1 的拷贝width、height、depth将分别包含值10、20、15。