Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 6 of 6
When an inner class references a local variable from the containing class, that variable must be declared as final. That restriction is imposed by Java so that the virtual machine and compiler do not have to worry about a variable that
could be simulatenously modified in two different classes. In this case, the only such variable accessed is first, which just happens to be final.
package enumTest; import java.util.*;
public final class Color { private String id; public final int ord; private Color prev; private Color next;
private static int upperBound = 0; private static Color first = null; private static Color last = null; private Color(String anID) { this.id = anID; this.ord = upperBound++; if (first == null) first = this; if (last != null) { this.prev = last; last.next = this; } last = this; } public static Enumeration elements() { return new Enumeration() { private Color curr = first; public boolean hasMoreElements() { return curr != null; } public Object nextElement() { Color c = curr; curr = curr.next(); return c; } }; } public String toString() {return this.id; } public static int size() { return upperBound; } public static Color first() { return first; } public static Color last() { return last; } public Color prev() { return this.prev; } public Color next() { return this.next; }
public static final Color RED = new Color("Red"); public static final Color GREEN = new Color("Green"); public static final Color BLUE = new Color("Blue"); }
Finally, here is a test file that shows what happens when you enumerate over the constants defined in the Color class:
package enumTest; import java.util.*;
public class EnumTest { //Main method static public void main(String[] args) { Enumeration e = Color.elements(); while (e.hasMoreElements()) { Color c = (Color) e.nextElement(); System.out.println(c + ": " + c.ord); } } }
Note: If compilation produces the error, "class Color not found," make sure your classpath variable includes "..". With the
Color class in the enumTest package, the compiler sees "Color" as "enumTest.Color." The installation instructions for JDK 1.1 say to include "." in the
classpath, but under Windows, at least, that causes the compiler to look for Color.java under the current directory (enumTest) instead of in that directory.