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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

468<br />

15.12.2.10 Example: Overloading Ambiguity<br />

Consider the example:<br />

class Point { int x, y; }<br />

class ColoredPoint extends Point { int color; }<br />

class Test {<br />

static void test(ColoredPoint p, Point q) {<br />

System.out.println("(ColoredPoint, Point)");<br />

}<br />

static void test(Point p, ColoredPoint q) {<br />

System.out.println("(Point, ColoredPoint)");<br />

}<br />

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

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

test(cp, cp); // compile-time error<br />

}<br />

}<br />

This example produces an error at compile time. <strong>The</strong> problem is that there are two<br />

declarations of test that are applicable and accessible, and neither is more specific<br />

than the other. <strong>The</strong>refore, the method invocation is ambiguous.<br />

If a third definition of test were added:<br />

static void test(ColoredPoint p, ColoredPoint q) {<br />

System.out.println("(ColoredPoint, ColoredPoint)");<br />

}<br />

then it would be more specific than the other two, and the method invocation<br />

would no longer be ambiguous.<br />

DRAFT<br />

15.12.2.11 Example: Return Type Not Considered<br />

As another example, consider:<br />

class Point { int x, y; }<br />

class ColoredPoint extends Point { int color; }<br />

class Test {<br />

static int test(ColoredPoint p) {<br />

return p.color;<br />

}<br />

static String test(Point p) {<br />

return "Point";<br />

}<br />

public static void main(String[] args) {

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

Saved successfully!

Ooh no, something went wrong!