Java Reference
In-Depth Information
PITFALL: Overloading and Automatic Type Conversion
Automatic type conversion of arguments (such as converting an
int
to a
double
when
the parameter is of type
double
) and overloading can sometimes interact in unfortu-
nate ways. So, you need to know how these two things interact.
For example, consider the following method that might be added to the class
DateSixthTry
in Display 4.11:
public void
increase(
double
factor)
{
year = (
int
)(year + factor*year);
}
If you add this method to the class
DateSixthTry
, then the following presents no prob-
lems, where
date
is an object of type
DateSixthTry
that has been set to some date:
date.increase(2);
The
int
value of
2
is type cast to the
double
value
2.0,
and the value of
date.year
is
changed as follows:
date.year = (
int
)(date.year + 2.0*date.year);
(Because
year
is private in the class
DateSixthTry
, you cannot write this in a program
that uses the class
DateSixthTry
, but the meaning of this expression is clear.)
So far, so good. But now suppose we also add the following method definition to
the class
DateSixthTry
:
public void
increase(
int
term)
{
year = year + term;
}
This is a valid overloading because the two methods named
increase
take parameters
of different types. With both of these methods named
increase
added to the class, the
following now behaves differently:
date.increase(2);
If Java can find an exact match of types, it uses the method definition with an exact
match before it tries to do any automatic type casts. So now the displayed invocation
of
date.increase
is equivalent to
date.year = date.year + 2;
However, if you meant to use an argument of
2.0
for
date.increase
and instead used
2
, counting on an automatic type cast, then this is not what you want. It is best to
avoid overloading where there is a potential for interacting dangerously with auto-
matic type casting, as in the examples discussed in this Pitfall section.