15.11.2
Compile Time Step 2: Determine Method Signature
EXPRESSIONS
class Test extends Doubler {
public static long two(long j) {return j+j; }
public static void main(String[] args) {
System.out.println(two(3));
System.out.println(Doubler.two(3)); //
compile time error
}
}
for the method invocation
two(1)
within class
Doubler
, there are two accessible
methods 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 method 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 conversion, which is used in the initialization of the variable
color
,
performs an implicit conversion 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 because method invocation conversion does permit a widening conver
sion from
byte
to
int
. However, a narrowing cast would then be required in the
body of
setColor
:
326
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved