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 />

236<br />

<strong>The</strong> subclass LineBufferOutput declares only a constructor and a single method<br />

putchar, which overrides the method putchar of BufferOutput. It inherits the<br />

methods putstr and flush from class BufferOutput.<br />

In the putchar method of a LineBufferOutput object, if the character argument<br />

is a newline, then it invokes the flush method. <strong>The</strong> critical point about overriding<br />

in this example is that the method putstr, which is declared in class<br />

BufferOutput, invokes the putchar method defined by the current object this,<br />

which is not necessarily the putchar method declared in class BufferOutput.<br />

Thus, when putstr is invoked in main using the LineBufferOutput object<br />

lbo, the invocation of putchar in the body of the putstr method is an invocation<br />

of the putchar of the object lbo, the overriding declaration of putchar that<br />

checks for a newline. This allows a subclass of BufferOutput to change the<br />

behavior of the putstr method without redefining it.<br />

Documentation for a class such as BufferOutput, which is designed to be<br />

extended, should clearly indicate what is the contract between the class and its<br />

subclasses, and should clearly indicate that subclasses may override the putchar<br />

method in this way. <strong>The</strong> implementor of the BufferOutput class would not,<br />

therefore, want to change the implementation of putstr in a future implementation<br />

of BufferOutput not to use the method putchar, because this would break<br />

the preexisting contract with subclasses. See the further discussion of binary compatibility<br />

in §13, especially §13.2.<br />

8.4.10.7 Example: Incorrect Overriding because of Throws<br />

This example uses the usual and conventional form for declaring a new exception<br />

type, in its declaration of the class BadPointException:<br />

class BadPointException extends Exception {<br />

BadPointException() { super(); }<br />

BadPointException(String s) { super(s); }<br />

}<br />

class Point {<br />

int x, y;<br />

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

}<br />

class CheckedPoint extends Point {<br />

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

if ((x + dx) < 0 || (y + dy) < 0)<br />

throw new BadPointException();<br />

x += dx; y += dy;<br />

}<br />

}<br />

DRAFT

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

Saved successfully!

Ooh no, something went wrong!