Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

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?

like image 809
Cheok Yan Cheng Avatar asked May 26 '18 18:05

Cheok Yan Cheng


People also ask

What is the purpose of enums enumerations in Java?

The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Can we have an enum within an enum?

yes, but you need to know that.

Can we have enum inside enum in Java?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.


2 Answers

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 
like image 158
Amit Bera Avatar answered Sep 24 '22 14:09

Amit Bera


Enum instance are just static instance of the enum class.

We have two way to access static field of a class:

  1. Via class itselft: Repeat.Daily
  2. Via instance of class: Repeat.Daily.Daily

When you chain your enum:

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

It's just like get a static field from an instance of a class.

like image 36
Mạnh Quyết Nguyễn Avatar answered Sep 24 '22 14:09

Mạnh Quyết Nguyễn