Java Reference
In-Depth Information
Sphere(double theRadius, double x, double y, double z) {
this(x, y, z);
// Call the 3 argument constructor
radius = theRadius;
// Set the radius
}
// The rest of the class as before...
}
In the constructor that accepts the point coordinates as arguments, you call the default constructor to set
the radius and increment the count of the number of objects. In the constructor that sets the radius, as well as
the coordinates, you call the constructor with three arguments to set the coordinates, which in turn call the
constructor that requires no arguments.
Duplicating Objects Using a Constructor
When you were looking at how objects were passed to a method, you came across a requirement for duplic-
ating an object. The need to produce an identical copy of an object occurs surprisingly often.
Suppose you declare a Sphere object with the following statement:
Sphere eightBall = new Sphere(10.0, 10.0, 0.0);
Later in your program you want to create a new object newBall , which is identical to the object
eightBall . If you write
Sphere newBall = eightBall;
this compiles okay, but it won't do what you want. You might remember from my earlier discussion that the
variable newBall references the same object as eightBall . You don't have a distinct object. The variable
newBall , of type Sphere , is created but no constructor is called, so no new object is created.
Of course, you could create newBall by specifying the same arguments to the constructor as you used to
create eightBall . In general, however, it may be that eightBall has been modified in some way during
execution of the program, so you don't know that its instance variables have the same values — for example,
the position might have changed. This presumes that you have some other class methods that alter the in-
stance variables. You could provide the capability for duplicating an existing object by adding a constructor
to the class that accepts an existing Sphere object as an argument:
// Create a sphere from an existing object
Sphere(final Sphere oldSphere) {
radius = oldSphere.radius;
xCenter = oldSphere.xCenter;
yCenter = oldSphere.yCenter;
zCenter = oldSphere.yCenter;
++count; // Increment the object count
}
This works by copying the values of the instance variables of the Sphere object that is passed as the ar-
gument to the corresponding instance variables of the new object. Thus the new object that this constructor
creates is identical to the Sphere object that is passed as the argument.
Now you can create newBall as a distinct object by writing:
Search WWH ::




Custom Search