THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Consider a variation of the Point class we introduced in Chapter 1. The natural ordering for points could be
their distance from the origin. We could then make Point objects Comparable:


class Point implements Comparable {


/* Origin reference that never changes /
private static final Point ORIGIN = new Point();


private int x, y;


// ... definition of constructors, setters and accessors


public double distance(Point p) {
int xdiff = x - p.x;
int ydiff = y - p.y;
return Math.sqrt(xdiff xdiff + ydiff ydiff);
}


public int compareTo(Point p) {
double pDist = p.distance(ORIGIN);
double dist = this.distance(ORIGIN);
if (dist > pDist)
return 1;
else if (dist == pDist)
return 0;
else
return -1;
}
}


First we declare that Point is a Comparable class. A class identifies the interface types that it implements
by listing them after the keyword implements, 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 superinterfaces, 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 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]


[1] In Chapter 11 you learn about generic methods, and sort should really be defined as
such.

class Sorter {
static Comparable<?>[] sort(Comparable<?>[] list) {
// implementation details ...
return list;
}
}

Free download pdf