3

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;
     }
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
Babanna Duggani
  • 737
  • 2
  • 12
  • 34

3 Answers3

5

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

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Let me confirm my understanding here, 1. You mean to say Enums are by default singleton and INSTANCE variable returns reference to singleton instance. 2. Singleton instance will be created for each of the constant like one for SUNDAY, one for MONDAY and so on...... . – Babanna Duggani Jul 17 '17 at 13:26
  • The second point is ok but the first one, no. Enum classes are just classes. The single singletons that this class provides are represented by enumerated values (SUNDAY, MONDAY, etc...) that you are declaring. – davidxxx Jul 17 '17 at 13:51
  • If Enums are not singleton by default, then how to make it singleton. Please advise as I am not clear yet. – Babanna Duggani Jul 18 '17 at 06:07
  • It is not so complicated : **Each enumerated value is a singleton. Not the enum class itself.** So when you declare `public enum Days { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;}` **you get 7 instances of Days** which **each one is a singleton**. – davidxxx Jul 18 '17 at 09:50
  • Got it sir. Thank you. – Babanna Duggani Jul 18 '17 at 10:14
1

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.

Austin Schaefer
  • 695
  • 5
  • 19
0

You cannot break the declaration of ENUM varriables and then continue again. Add INSTANCE to the 3th row with comma and you will be able to compile the program.

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

TreantBG
  • 1,192
  • 6
  • 25
  • 44