Java Reference
In-Depth Information
Click here to view code image
class Point {
int x = 0, y = 0, color;
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
int getY() { return y; }
}
class RealPoint extends Point {
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
float getX() { return x; }
float getY() { return y; }
}
Here, the class Point provides methods getX and getY that return the values of its fields
x and y ; the class RealPoint then overrides these methods by declaring methods with the
same signature. The result is two errors at compile time, one for each method, because
the return types do not match; the methods in class Point return values of type int , but
the wanna-be overriding methods in class RealPoint return values of type float .
This program corrects the errors of the preceding program:
Click here to view code image
class Point {
int x = 0, y = 0;
void move(int dx, int dy) { x += dx; y += dy; }
int getX() { return x; }
int getY() { return y; }
int color;
}
class RealPoint extends Point {
float x = 0.0f, y = 0.0f;
void move(int dx, int dy) { move((float)dx, (float)dy); }
void move(float dx, float dy) { x += dx; y += dy; }
int getX() { return (int)Math.floor(x); }
int getY() { return (int)Math.floor(y); }
}
Here, the overriding methods getX and getY in class RealPoint have the same return
types as the methods of class Point that they override, so this code can be successfully
compiled.
Consider, then, this test program:
Search WWH ::




Custom Search