1

I have a Java Singleton class as :

public enum MyClass{
   INSTANCE;

   private MyClass(){
     init();
   } 

   private static void init(){
     System.out.println("Singleton Class initiated");
   }
}

When I try to instantiate the class by :

MyClass.INSTANCE;

I get an error that it is not a statement.

However, the following works, which is not ideal for production code:

System.out.println(MyClass.INSTANCE);

Is there a way to initiate the enum singleton class properly, without calling any other dummy API of the class?

Aadhirai R
  • 141
  • 9

2 Answers2

2

Just state class ( or enum in your case) isn't a valid Java statement.

You can create an object as @Lorelorelore suggested

MyClass instance = MyClass.INSTANCE;

Or if you want to call init() maybe change its signature

public void init(){
    System.out.println("Singleton Class initiated");
}

And call the method directly:

MyClass.INSTANCE.init();
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

As I said in my comment: simply declare it in this way:

MyClass instance = MyClass.INSTANCE;
Lorelorelore
  • 3,335
  • 8
  • 29
  • 40