Java Reference
In-Depth Information
super.move(limit(dx, xLimit), limit(dy, yLimit));
}
static int limit(int d, int limit) {
return d > limit ? limit : d < -limit ? -limit : d;
}
}
Here, the class SlowPoint overrides the declarations of method move of class Point with
its own move method, which limits the distance that the point can move on each in-
vocation of the method. When the move method is invoked for an instance of class
SlowPoint , the overriding definition in class SlowPoint will always be called, even if the
reference to the SlowPoint object is taken from a variable whose type is Point .
Example 8.4.8.1-2. Overriding
Overriding makes it easy for subclasses to extend the behavior of an existing class, as
shown in this example:
Click here to view code image
import java.io.OutputStream;
import java.io.IOException;
class BufferOutput {
private OutputStream o;
BufferOutput(OutputStream o) { this.o = o; }
protected byte[] buf = new byte[512];
protected int pos = 0;
public void putchar(char c) throws IOException {
if (pos == buf.length) flush();
buf[pos++] = (byte)c;
}
public void putstr(String s) throws IOException {
for (int i = 0; i < s.length(); i++)
putchar(s.charAt(i));
}
public void flush() throws IOException {
o.write(buf, 0, pos);
pos = 0;
}
}
class LineBufferOutput extends BufferOutput {
LineBufferOutput(OutputStream o) { super(o); }
public void putchar(char c) throws IOException {
super.putchar(c);
if (c == '\n') flush();
}
Search WWH ::




Custom Search