Steven said:
I was trying to help out with this question in comp.lang.java.help but
am more confused by the implementation of Enums than I was when I
started. I thought I would cross post this to the programmer group to
get more eyes.
Can anyone give a brief overview of Enums in Java 5? They appear to be
more complex than their C++ friends.
--Steve
A java enum is a typesafe set of values. It's a singleton class that has
a special way of creating predefined instances.
Yes it does. 3.1 reports public enum constructors as an error. And they
are (otherwise you'd destroy the singleton property - ie. you arent
supposed to be able to just create new types of the enum - they are
predefined in the enum body).
While each enum member has no intrisnic value (Days.SUNDAY is
Days.SUNDAY - nothing else), you can assign values to them.
// -- example:
public class EnumDemo {
public enum Colour {
RED (0x00FF0000),
GREEN (0x0000FF00),
BLUE (0x000000FF);
private int argb;
private Colour( int argb ) {
this.argb = argb;
}
public int getARGB() {
return argb;
}
}
public static void main(String... args) {
for (Colour colour : Colour.values()) {
System.out.printf("%1$s\t0x%2$08x\n",
colour.name(),colour.getARGB());
}
}
}
//--
expected output:
RED 0x00ff0000
GREEN 0x0000ff00
BLUE 0x000000ff
Notice how the enum is essentially a class with no way to create a new
instance (the only instances in this case are RED, GREEN and BLUE). To
be able to create a new instance, say YELLOW, you would have to define
it in the enum. It wouldn't make sense to have a way of doing: Colour
YELLOW = new Colour(0x00FFFF00); because this "YELLOW" wouldn't be a
part of the enum. You'd want to add it to the enum.
The old java way of doing it (public final static int VALUE = 0
lacked
the ability to enumerate over the defined values (see the
Colour.values() in the above example).
Enums should be treated as a fixed set of constants - nothing else. It
also means they are safe for serialization because it stores the value
as the type (eg. Colour.RED is stored as Colour.RED and not, say 1). You
can add new types and not worry about reading back serialized data
(since it stored Colour.RED and not 1).
I recommend looking over the api docs if you haven't already:
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html