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 enums special:

  1. the compiler knows enums have fixed list of instances. allows things emit warnings if switch doesn't have case statement handle each value.
  2. 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 structures enummap created.

i'm sure i'm missing few things, place start.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -