Java Reference
In-Depth Information
In this version, since there is a version of
f( )
that takes a
byte
argument, when
f( )
is called
with a
byte
argument,
f(byte)
is invoked and the automatic conversion to
int
does not oc-
cur.
Method overloading supports polymorphism because it is one way that Java implements
the “one interface, multiple methods” paradigm. To understand how, consider the follow-
ing: In languages that do not support method overloading, each method must be given a
unique name. However, frequently you will want to implement essentially the same meth-
od for different types of data. Consider the absolute value function. In languages that do
not support overloading, there are usually three or more versions of this function, each with
a slightly different name. For instance, in C, the function
abs( )
returns the absolute value
of an integer,
labs( )
returns the absolute value of a long integer, and
fabs( )
returns the ab-
solute value of a floating-point value. Since C does not support overloading, each function
has to have its own name, even though all three functions do essentially the same thing.
This makes the situation more complex, conceptually, than it actually is. Although the un-
derlying concept of each function is the same, you still have three names to remember.
This situation does not occur in Java, because each absolute value method can use the same
name. Indeed, Java's standard class library includes an absolute value method, called
abs(
)
. This method is overloaded by Java's
Math
class to handle all of the 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 com-
mon name. Thus, the name
abs
represents the
general action
that is being performed. It is
left to the compiler to choose the correct
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 ex-
ample is fairly simple, if you expand the concept, you can see how overloading can help
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 ex-
ample, 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