Why do we allow referring to an enum member of an enum member in Java?

  • A+
Category:Languages

Given the following enum:

enum Repeat {     Daily,     Weekly,     Yearly } 

I realize we are able to write it this way:

Repeat repeat = Repeat.Daily.Weekly.Yearly.Weekly; 

which is equivalent to:

Repeat repeat = Repeat.Weekly; 

May I know why such syntax is allowed? Is there a way to let the compiler warn us against this?


This is allowed as Daily, Weekly, Yearly are the static field by default inside the enum and holds the object of Repeat. Also, you will get a warning from the compiler "The static field Repeat.Weekly should be accessed in a static way". It is similar to below lines of code.

class Foo{     public static Foo obj1 = new Foo();     public static Foo obj2 = new Foo();     public static Foo obj3 = new Foo(); }  Foo f = Foo.obj1.obj2.obj3; // will work fine but you will get a warning from the compiler. 

Here is some part of bytecode inspection of Repeat enum and from this, it is clear that Enum variable is static and holds the Object of Enum itself.

   0: new           #1                  // class com/java8/demo/Repeat    3: dup    4: ldc           #14                 // String Daily    6: iconst_0    7: invokespecial #15                 // Method "<init>":(Ljava/lang/String;I)V   10: putstatic     #19                 // Field Daily:Lcom/java8/demo/Repeat;   13: new           #1                  // class com/java8/demo/Repeat  

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: