Java Reference
In-Depth Information
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 ex-
ample. There is a version of this method for each of the basic types. One context in which you regularly
need to use overloading is when you write constructors for your classes, which will I explain now.
Multiple Constructors
Constructors are methods that can be overloaded, just like any other method in a class. In most situations,
you want to generate objects of a class from different sets of initial defining data. If you just consider the
Sphere class, you 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 you have already written. Let's try it.
TRY IT OUT: Multiple Constructors for the Sphere Class
I suggest you put the files for this example in the Create Spheres 2 directory. The code for the extra
constructors is as follows:
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...
}
Search WWH ::




Custom Search