Java Reference
In-Depth Information
If you try adding this to the Sphere class and recompile, you'll get a compile-time error. This
constructor has four arguments of type double , so its signature is identical to the first constructor that
we wrote for the class. This is not permitted - hence the compile-time error. When the number of
parameters is the same in two overloaded methods, at least one pair of corresponding parameters must
be of different types.
Calling a Constructor from a Constructor
One class constructor can call another constructor in the same class in its first executable statement.
This can often save duplicating a lot of code. To refer to another constructor in the same class, you use
this as the name, followed by the appropriate arguments between parentheses. In our Sphere class,
we could have defined the constructors as:
class Sphere {
// Construct a unit sphere at the origin
Sphere() {
radius = 1.0;
// Other data members will be zero by default
++count; // Update object count
}
// Construct a unit sphere at a point
Sphere(double x, double y, double z)
{
this(); // Call the constructor with no arguments
xCenter = x;
yCenter = y;
zCenter = z;
}
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 argument, we 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, the constructor with three arguments is called to set the coordinates, which in
turn will call the constructor that requires no arguments.
Duplicating Objects Using a Constructor
When we were looking at how objects were passed to a method, we came up with a requirement for
duplicating an object. The need to produce an identical copy of an object occurs surprisingly often.
Java provides a clone() method, but the details of using it must wait for the
next chapter.
Search WWH ::




Custom Search