Java Reference
In-Depth Information
When you create a Sphere object, the compiler selects the constructor to use based on the types of the
arguments you have specified. So, the first of the new constructors is applied in the first statement that
you added to main() , as its signature fits with the argument types used. The second statement that you
added clearly selects the last constructor, as no arguments are specified. The other additional statements
are there just to generate some output corresponding to the new objects. You can see from the volumes
of eightBall and oddBall that they both are of radius 1 — in both instances the result is the value of
4π/3.
It is the number and types of the parameters that affect the signature of a method, not the parameter
names. If you want a constructor that defines a Sphere object at a point, by specifying the diameter rather
than the radius, you have a problem. You might try to write it as:
// Illegal constructor!!!
// This WON'T WORK because it has the same signature as the
original!!!
Sphere(double diameter, double x, double y, double z) {
xCenter = x;
yCenter = y;
zCenter = z;
radius = diameter/2.0;
++count;
}
If you add this method to the Sphere class and recompile, you get a compile-time error. This constructor
has four arguments of type double , so its signature is identical to the first constructor that you 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
method name, followed by the appropriate arguments between parentheses. In the Sphere class, you 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;
}
Search WWH ::




Custom Search