*/
class Box {
double width; double height; double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume double volume() { return width * height * depth;}}
class BoxDemo6 {
public static void main(String args[]) { // declare,allocate,and initialize Box objectsBox mybox1 = new Box();Box mybox2 = new Box();
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);
}
}
运行该程序,产生如下的结果:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
正如你能看到的一样,当mybox1 和mybox2 被创建时,它们两个都被Box 构造函数初始化。因为构造函数将所有的盒子赋为一样的尺寸,长、宽、高都是10,mybox1 和 mybox2 将有一样的体积。在Box( )内的println( ) 语句仅仅是为说明的缘故。大多数构造函数的功能不显示任何东西,他们仅简单地初始化一个对象。
在继续学习前,让我们再考察new运算符。你已经知道,当分配一个对象时,使用下面的通用格式:
class-var = new classname( );
现在你可以理解为什么在类的名字后面需要圆括号。圆括号的作用是调用该类的构造函数。这样,在下面的这行中
Box mybox1 = new Box();
new Box( ) 调用Box( )构造函数。如果你不显式为类定义一个构造函数,Java 将为该类创建一个默认的构造函数。这就是本行程序在Box早期版本没有定义构造函数工作的原因。
默认构造函数自动地将所有的实例变量初始化为零。默认构造函数对简单的类是足够的,但是对更复杂的类它就不能满足要求了。一旦你定义了你自己的构造函数,默认构造函数将不再被使用。
6.5.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 objectsBox mybox1 = new Box(10,20,15);Box mybox2 = new Box(3,6,9);
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(10,20,15);
当new创建对象时,值10,20,15传递到Box() 构造函数。这样,mybox1 的拷贝width 、height 、depth 将分别包含值10、20、15。








