standard class library includes an absolute value method, called abs( ). This method is
overloaded by Java's Math class to handle all numeric types. Java determines which version
of abs( ) to call based upon the type of argument.
The value of overloading is that it allows related methods to be accessed by use of a
common name. Thus, the name abs represents the general action that is being performed. It
is left to the compiler to choose the right specific version for a particular circumstance. You,
the programmer, need only remember the general operation being performed. Through the
application of polymorphism, several names have been reduced to one. Although this
example is fairly simple, if you expand the concept, you can see how overloading can help
you manage greater complexity.
When you overload a method, each version of that method can perform any activity
you desire. There is no rule stating that overloaded methods must relate to one another.
However, from a stylistic point of view, method overloading implies a relationship. Thus,
while you can use the same name to overload unrelated methods, you should not. For
example, you could use the name sqr to create methods that return the square of an integer
and the square root of a floating-point value. But these two operations are fundamentally
different. Applying method overloading in this manner defeats its original purpose. In
practice, you should only overload closely related operations.
Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods. In
fact, for most real-world classes that you create, overloaded constructors will be the norm,
not the exception. To understand why, let's return to the Box class developed in the preceding
chapter. Following is the latest version of Box:
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
As you can see, the Box( ) constructor requires three parameters. This means that all
declarations of Box objects must pass three arguments to the Box( ) constructor. For example,
the following statement is currently invalid:
Box ob = new Box();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home