8.4.8
Examples of Method Declarations
CLASSES
Documentation for a class such as
BufferOutput
, which is designed to be
extended, should clearly indicate what is the contract between the class and its
subclasses, and should clearly indicate that subclasses may override the
putchar
method in this way. The implementor of the
BufferOutput
class would not,
therefore, want to change the implementation of
putstr
in a future implementa
tion of
BufferOutput
not to use the method
putchar
, because this would break
the preexisting contract with subclasses. See the further discussion of binary com
patibility in 13, especially 13.2.
8.4.8.7
Example: Incorrect Overriding because of Throws
This example uses the usual and conventional form for declaring a new exception
type, in its declaration of the class
BadPointException
:
class BadPointException extends Exception {
BadPointException() { super(); }
BadPointException(String s) { super(s); }
}
class Point {
int x, y;
void move(int dx, int dy) { x += dx; y += dy; }
}
class CheckedPoint extends Point {
void move(int dx, int dy) throws BadPointException {
if ((x + dx) < 0 || (y + dy) < 0)
throw new BadPointException();
x += dx; y += dy;
}
}
This example results in a compile time error, because the override of method
move
in class
CheckedPoint
declares that it will throw a checked exception that
the
move
in class
Point
has not declared. If this were not considered an error, an
invoker of the method
move
on a reference of type
Point
could find the contract
between it and
Point
broken if this exception were thrown.
Removing the
throws
clause does not help:
class CheckedPoint extends Point {
void move(int dx, int dy) {
if ((x + dx) < 0 || (y + dy) < 0)
throw new BadPointException();
x += dx; y += dy;
}
}
174
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved