Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 6: Introducing Classes 119


As you can see, bothmybox1andmybox2were initialized by theBox( )constructor when
they were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10,
bothmybox1andmybox2will have the same volume. Theprintln( )statement insideBox( )
is for the sake of illustration only. Most constructors will not display anything. They will
simply initialize an object.
Before moving on, let’s reexamine thenewoperator. As you know, when you allocate an
object, you use the following general form:


class-var= newclassname( );

Now you can understand why the parentheses are needed after the class name. What is actually
happening is that the constructor for the class is being called. Thus, in the line


Box mybox1 = new Box();


new Box( )is calling theBox( )constructor. When you do not explicitly define a constructor
for a class, then Java creates a default constructor for the class. This is why the preceding line
of code worked in earlier versions ofBoxthat did not define a constructor. The default
constructor automatically initializes all instance variables to zero. The default constructor is
often sufficient for simple classes, but it usually won’t do for more sophisticated ones. Once
you define your own constructor, the default constructor is no longer used.


Parameterized Constructors


While theBox( )constructor in the preceding example does initialize aBoxobject, it is not
very useful—all boxes have the same dimensions. What is needed is a way to constructBox
objects of various dimensions. The easy solution is to add parameters to the constructor. As
you can probably guess, this makes them much more useful. For example, the following version
ofBoxdefines a parameterized constructor that sets the dimensions of a box as specified by
those parameters. Pay special attention to howBoxobjects are created.


/ 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;
}
}

Free download pdf