10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

EXPRESSIONS Compile-Time Step 2: Determine Method Signature 15.12.2<br />

public static long two(long j) {return j+j; }<br />

public static void main(String[] args) {<br />

System.out.println(two(3));<br />

System.out.println(Doubler.two(3)); // compile-time error<br />

}<br />

}<br />

for the method invocation two(1) within class Doubler, there are two accessible<br />

methods named two, but only the second one is applicable, and so that is the one<br />

invoked at run time. For the method invocation two(3) within class Test, there<br />

are two applicable methods, but only the one in class Test is accessible, and so<br />

that is the one to be invoked at run time (the argument 3 is converted to type<br />

long). For the method invocation Doubler.two(3), the class Doubler, not class<br />

Test, is searched for methods named two; the only applicable method is not<br />

accessible, and so this method invocation causes a compile-time error.<br />

Another example is:<br />

class ColoredPoint {<br />

int x, y;<br />

byte color;<br />

void setColor(byte color) { this.color = color; }<br />

}<br />

class Test {<br />

public static void main(String[] args) {<br />

ColoredPoint cp = new ColoredPoint();<br />

byte color = 37;<br />

cp.setColor(color);<br />

cp.setColor(37); // compile-time error<br />

}<br />

}<br />

Here, a compile-time error occurs for the second invocation of setColor, because<br />

no applicable method can be found at compile time. <strong>The</strong> type of the literal 37 is<br />

int, and int cannot be converted to byte by method invocation conversion.<br />

Assignment conversion, which is used in the initialization of the variable color,<br />

performs an implicit conversion of the constant from type int to byte, which is<br />

permitted because the value 37 is small enough to be represented in type byte;but<br />

such a conversion is not allowed for method invocation conversion.<br />

If the method setColor had, however, been declared to take an int instead of<br />

a byte, then both method invocations would be correct; the first invocation would<br />

be allowed because method invocation conversion does permit a widening conversion<br />

from byte to int. However, a narrowing cast would then be required in the<br />

body of setColor:<br />

void setColor(int color) { this.color = (byte)color; }<br />

DRAFT<br />

467

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!