Java Reference
In-Depth Information
PITFALL: (continued)
In some cases of overloading, a single method invocation can be resolved in two
different ways, depending on how overloading and type conversion interact. Such
ambiguous method invocations are not allowed in Java and will produce an error
message. For example, you can overload a method named doSomething by giving
two definitions that have the following two method headings in a SampleClass :
public class SampleClass
{
public void doSomething( double n1, int n2)
.
.
.
public void doSomething( int n1, double n2)
.
.
.
Such overloading is legal, but there is a problem. Suppose aSampleObject is an object
of type SampleClass . An invocation such as the following will produce an error
message, because Java cannot decide which overloaded definition of doSomething
to use:
aSampleObject.doSomething(5, 10);
Java cannot decide whether it should convert the int value 5 to a double value
and use the first definition of doSomething , or whether it should convert the int
value 10 to a double value and use the second definition. In this situation, the Java
compiler issues an error message indicating that the method invocation is ambiguous.
The following two method invocations are allowed:
aSampleObject.doSomething(5.0, 10);
aSampleObject.doSomething(5, 10.0);
However, such situations, while legal, are confusing and should be avoided.
Display 4.12
Using an Overloaded Method Name (part 1 of 2)
1 public class OverloadingDemo
2{
3 public static void main(String[] args)
4 {
5 DateSixthTry date1 = new DateSixthTry(),
6 date2 = new DateSixthTry(),
7 date3 = new DateSixthTry();
(continued)
Search WWH ::




Custom Search