An enum
is a class that inherits from the Enum
class with (a) a private
constructor, as you mentioned; and (b) a fixed, ordered list of named, final
instances.
Under the covers, when you declare an enum
:
public enum Foo {
A(1) {
public void bar() {
System.out.println("A#bar");
}
},
B(2) {
public void bar() {
System.out.println("B#bar");
}
},
C(3) {
public void bar() {
System.out.println("C#bar");
}
};
private Foo(int x) {
// Code goes here...
}
public abstract void bar();
}
...you can imagine the compiler generates something like this:
public class Foo extends Enum<Foo> {
public static final Foo A=new Foo(1) {
public void bar() {
System.out.println("A#bar");
}
};
public static final Foo B=new Foo(2) {
public void bar() {
System.out.println("B#bar");
}
};
public static final Foo C=new Foo(3) {
public void bar() {
System.out.println("C#bar");
}
};
private Foo(int x) {
// Code goes here...
}
}
There are a couple other things that make enum
s special:
- The compiler knows that
enum
s have a fixed list of instances. This allows it to do things like emit warnings if a switch
doesn't have a case
statement to handle each value.
- Each constant has a special, compiler-generated, 0-based, monotonically increasing, dense
ordinal()
value assigned to it. (In other words, the first has ordinal 0, then second has ordinal 1, and so on.) This allows for extremely efficient array-based data structures like EnumMap
to be created.
I'm sure I'm missing a few things, but this is a good place to start.