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.

8.4.10 Examples of Method Declarations CLASSES<br />

232<br />

class RealPoint extends Point {<br />

float x = 0.0f, y = 0.0f;<br />

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

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

float getX() { return x; }<br />

float getY() { return y; }<br />

}<br />

Here the class Point provides methods getX and getY that return the values of its<br />

fields x and y; the class RealPoint then overrides these methods by declaring<br />

methods with the same signature. <strong>The</strong> result is two errors at compile time, one for<br />

each method, because the return types do not match; the methods in class Point<br />

return values of type int, but the wanna-be overriding methods in class<br />

RealPoint return values of type float.<br />

8.4.10.4 Example: Overriding versus Hiding<br />

This example corrects the errors of the example in the preceding section:<br />

class Point {<br />

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

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

int getX() { return x; }<br />

int getY() { return y; }<br />

int color;<br />

}<br />

class RealPoint extends Point {<br />

DRAFT<br />

float x = 0.0f, y = 0.0f;<br />

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

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

int getX() { return (int)Math.floor(x); }<br />

int getY() { return (int)Math.floor(y); }<br />

}<br />

Here the overriding methods getX and getY in class RealPoint have the same<br />

return types as the methods of class Point that they override, so this code can be<br />

successfully compiled.

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

Saved successfully!

Ooh no, something went wrong!