Java Reference
In-Depth Information
For the method invocation
two(1)
within class
Doubler
, there are two accessible meth-
ods named
two
, but only the second one is applicable, and so that is the one invoked
at run time.
For the method invocation
two(3)
within class
Test
, there are two applicable methods,
but only the one in class
Test
is accessible, and so that is the one to be invoked at run
time (the argument
3
is converted to type
long
).
For the method invocation
Doubler.two(3)
, the class
Doubler
, not class
Test
, is searched
for methods named
two
; the only applicable method is not accessible, and so this meth-
od invocation causes a compile-time error.
Another example is:
class ColoredPoint {
int x, y;
byte color;
void setColor(byte color) { this.color = color; }
}
class Test {
public static void main(String[] args) {
ColoredPoint cp = new ColoredPoint();
byte color = 37;
cp.setColor(color);
cp.setColor(37); // compile-time error
}
}
Here, a compile-time error occurs for the second invocation of
setColor
, because no
applicable method can be found at compile time. The type of the literal
37
is
int
, and
int
cannot be converted to
byte
by method invocation conversion. Assignment conver-
sion, which is used in the initialization of the variable
color
, performs an implicit con-
version of the constant from type
int
to
byte
, which is permitted because the value
37
is
small enough to be represented in type
byte
; but such a conversion is not allowed for
method invocation conversion.
If the method
setColor
had, however, been declared to take an
int
instead of a
byte
, then
both method invocations would be correct; the first invocation would be allowed be-
cause method invocation conversion does permit a widening conversion from
byte
to
int
. However, a narrowing cast would then be required in the body of
setColor
:
void setColor(int color) { this.color = (byte)color; }
Here is an example of overloading ambiguity. Consider the program: