Inner Classes Specification
Further Example: An API with coordinated inner classes
Note: This Inner Classes Specification is available for download as part of the JDK1.1 End Of Life (EOL) section of the Sun website. It has been included here because most of the specification is still relevant to the current Java classfile definition. However, the information has not been transferred into the latest Java Virtual Machine Specification or made available elsewhere in Sun's online Java resources.
Sometimes a class-based API will include as an essential feature secondary
classes or interfaces. These latter can be structured quite naturally as static
inner classes of the main class.
To see an example of this, imagine a hypothetical utility Sort with an interface
Comparer which virtualizes the comparison operation, and a handful of
standard reusable comparison implementations. (This example has a flaw:
Comparer is generic enough to stand alone.) The code might look like this:
public class Sorter {
public interface Comparer {
/** Returns <0 if x < y, etc. */
int compare(Object x, Object y);
}
public static void sort(Object keys[], Comparer c) {...}
public static void sort(Object keys[], Comparer c,
Object values[]) {...}
public static void sort(String keys[], Object values[])
{ sort(keys, stringComparer, values); }
public static class StringComparer implements Comparer {
public int compare(Object x, Object y) {
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
return x.toString().compareTo(y.toString());
}
}
public static final Comparer stringComparer
= new StringComparer();
public static class LongComparer implements Comparer {
... long lx = ((Number)x).longValue(); ...
}
public static final Comparer longComparer
= new LongComparer();
/** Compose 2 comparisons, presumably on distinct sub-keys. */
public static class CombinedComparer implements Comparer {...}
public static Comparer combine(Comparer c1, Comparer c2) {...}
...
}
|
|