0

What's wrong with below enum declaration? I want to write a singleton enum, so declared INSTANCE.

I get errors - "misplaced construct(s)"

public enum demo {
  INSTANCE;
  WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

  private int code;

  private demo(int c) {
    code = c;
  }

  private demo() { }

  public int getCode() {
    return code;
  }
}

2 Answers 2

3

In order to get it compiling, just replace the ; with ,, as you haven't finished listing the constants.

Something like this:

INSTANCE,
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

However, since you want to have a singleton, I suggest to get rid of the INSTANCE value, and introduce a static member that will hold the instance:

public static Demo INSTANCE = Demo.WHITE;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Please explain how the last line works? why we are using only WHITE in the ctor?
Looks like i need to read about enums more, can you plz recommend any resource?
3

You cannot declare two sets of instances within one enum class as you've done.

It isn't clear why you want an enum singleton of an enum, but if you want one INSTANCE to be a singleton, then you can declare a static variable to be one of the instances.

enum Demo {
    WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

    public static Demo INSTANCE = WHITE;

    // rest unchanged except for demo->Demo
}

It's possible to use the enum singleton pattern:

enum DemoSingleton
{
    INSTANCE(Demo.WHITE);

    private Demo myDemo;
    private DemoSingleton(Demo demo) { myDemo = demo; }
}

But that would be useless; you could just use Demo.WHITE.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.