Contents | Prev | Next Inner Classes Specification


Further Example: An API with coordinated inner classes

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) {...} ... }


Contents | Prev | Next

Inner Classes Specification (HTML generated by dkramer on March 15, 1997)
Copyright © 1996, 1997 Sun Microsystems, Inc. All rights reserved
Please send any comments or corrections to john.rose@eng.sun.com