Java Reference
In-Depth Information
There are many circumstances where it is convenient to use method overloading. You have already
seen that the standard class Math contains two versions of the method round() , one that accepts an
argument of type float , and the other that accepts an argument of type double . You can see now that
method overloading makes this possible. It would be rather tedious to have to use a different name for
each version of round() when they both do essentially the same thing. The valueOf() method in the
String class is another example. There is a version of this method for each of the basic types. One
context in which you will regularly need to use overloading is when you write constructors for your
classes, which we'll look at now.
Multiple Constructors
Constructors are methods that can be overloaded, just like any other method in a class. In most
situations, you will need to generate objects of a class from different sets of initial defining data. If we
just consider our class Sphere , we could conceive of a need to define a Sphere object in a variety of
ways. You might well want a constructor that accepted just the (x, y, z) coordinates of a point, and have
a Sphere object created with a default radius of 1.0. Another possibility is that you may want to create
a default Sphere with a radius of 1.0 positioned at the origin, so no arguments would be specified at all.
This requires two constructors in addition to the one we have already written.
Try It Out - Multiple Constructors for the Sphere Class
The code for the extra constructors is:
class Sphere {
// First Constructor and variable declarations
...
// Construct a unit sphere at a point
Sphere(double x, double y, double z) {
xCenter = x;
yCenter = y;
zCenter = z;
radius = 1.0;
++count; // Update object count
}
// Construct a unit sphere at the origin
Sphere() {
xCenter = 0.0;
yCenter = 0.0;
zCenter = 0.0;
radius = 1.0;
++count; // Update object count
}
// The rest of the class as before...
}
The statements in the default constructor that set three data members to zero are not really necessary, as
the data members would be set to zero by default. They are there just to emphasize that the primary
purpose of a constructor is to enable you to set initial values for the data members.
If you add the following statements to the CreateSpheres class, you can test out the new
constructors:
Search WWH ::




Custom Search