java - What exactly is an Enum? -
right i'm trying figure out enum in java. know how work , how/when use them i'm little unclear on are. based on behavior seems me nothing more class private constructor. seems me compiler doing special them enums have special method called values()
doesn't show in enum class on oracle doc site.
my question is, enums , how compiler interpret them?
an enum
class inherits enum
class (a) private
constructor, mentioned; , (b) fixed list of named, final
instances.
under covers, when declare 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 compiler generates 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 couple other things make enum
s special:
- the compiler knows
enum
s have fixed list of instances. allows things emit warnings ifswitch
doesn't havecase
statement handle each value. - each constant has special, compiler-generated, 0-based, monotonically increasing, dense
ordinal()
value assigned it. (in other words, first has ordinal 0, second has ordinal 1, , on.) allows extremely efficient array-based data structuresenummap
created.
i'm sure i'm missing few things, place start.
Comments
Post a Comment