Java Reference
In-Depth Information
class StringSorter {
// turns a collection of strings into a sorted list
List toList(Collection c) {...}
}
and assume that someone subclasses
StringSorter
:
class Overrider extends StringSorter {
List toList(Collection c) {...}
}
Now, at some point the author of
StringSorter
decides to generify the code:
class StringSorter {
// turns a collection of strings into a sorted list
List<String> toList(Collection<String> c) {...}
}
An unchecked warning would be given when compiling
Overrider
against the new
definition of
StringSorter
because the return type of
Overrider.toList
is
List
, which is not a
subtype of the return type of the overridden method,
List<String>
.
Example 8.4.8.3-3. Incorrect Overriding because of
throws
This program 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;
}
}