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.

8.4.10 Examples of Method Declarations CLASSES<br />

230<br />

time error. <strong>The</strong>re is no required relationship between the return types or between<br />

the throws clauses of two methods with the same name, unless their signatures<br />

are override-equivalent.<br />

Methods are overridden on a signature-by-signature basis.<br />

If, for example, a class declares two public methods with the same name,<br />

and a subclass overrides one of them, the subclass still inherits the other method.<br />

When a method is invoked (§15.12), the number of actual arguments (and any<br />

explicit type arguments) and the compile-time types of the arguments are used, at<br />

compile time, to determine the signature of the method that will be invoked<br />

(§15.12.2). If the method that is to be invoked is an instance method, the actual<br />

method to be invoked will be determined at run time, using dynamic method<br />

lookup (§15.12.4).<br />

8.4.10 Examples of Method Declarations<br />

<strong>The</strong> following examples illustrate some (possibly subtle) points about method<br />

declarations.<br />

8.4.10.1 Example: Overriding<br />

In the example:<br />

class Point {<br />

int x = 0, y = 0;<br />

void move(int dx, int dy) { x += dx; y += dy; }<br />

}<br />

class SlowPoint extends Point {<br />

int xLimit, yLimit;<br />

void move(int dx, int dy) {<br />

super.move(limit(dx, xLimit), limit(dy, yLimit));<br />

}<br />

static int limit(int d, int limit) {<br />

return d > limit ? limit : d < -limit ? -limit : d;<br />

}<br />

}<br />

the class SlowPoint overrides the declarations of method move of class Point<br />

with its own move method, which limits the distance that the point can move on<br />

each invocation of the method. When the move method is invoked for an instance<br />

of class SlowPoint, the overriding definition in class SlowPoint will always be<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!