Java Reference
In-Depth Information
First we declare that
Point
is a
Comparable
class. A class identifies the
interface types that it implements by listing them after the keyword
im-
plements
, before the class body is defined (and after any
extends
clause).
All such interfaces are the
superinterfaces
of the class. The class must
provide an implementation for all of the methods defined in its superint-
erfaces, or else the class must be declared
abstract
, thereby requiring
that any non-abstract subclass implement them.
The only method we need to implement for the
Comparable
interface is
compareTo
, and to actually compare two points we simply compare their
distance from the origin.
Interfaces introduce type names just as classes do, so you can declare
variables of those types. For example:
Comparable<Point> p1;
In fact much of the power of interfaces comes from declaring and using
only variables of interface type rather than of some specific class type.
For example, you can define a general-purpose
sort
routine that can
sort any array of
Comparable
objects without regard to what the class of
those objects actually isall the objects in the array should be the same
type of course:
[1]
class Sorter {
static Comparable<?>[] sort(Comparable<?>[] list) {
// implementation details ...
return list;
}
}