Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton enum with constants

I am trying to create enum with few constants. I want the enum to be singleton. With below code, I am getting compilation error in eclipse :

Syntax error, insert ")"

to complete the method declaration at line 5. I am not able to find out whats wrong.

public enum Days {

      SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;

      INSTANCE; // line 5

      public Days getInstance() {
        return INSTANCE;
     }
}
like image 697
Babanna Duggani Avatar asked Jun 13 '26 21:06

Babanna Duggani


2 Answers

In the enum declaration, ; is used after the last enumerated value.

So here :

SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;  
INSTANCE;

this should be removed :

INSTANCE;

I want the enum to be singleton

It is already the case but for enum values (SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY) which each one is a singleton.

The enum class itself is not a singleton and is not designed to be it.

Instead of trying to access the enum class in this way :

public Days getInstance() {
  return INSTANCE;
}

Use just the class : Days

like image 66
davidxxx Avatar answered Jun 16 '26 12:06

davidxxx


Remove the INSTANCE line, and access your enum statically like so: Days.MONDAY.

Enums aren't meant to be instantiated, which means there is no point to trying to make your enum a singleton.

like image 35
Austin Schäfer Avatar answered Jun 16 '26 11:06

Austin Schäfer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!