Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call methods within Java Singleton enum constructor?

My sample enum Singleton class is:

public class Test{

    public enum MyClass{

        INSTANCE;

        private static String name = "Hello";

        MyClass() {
            test();
        }

        private static void test(){
            name = name + "World";
            System.out.println(name);
        }
    }

    public static void main(String a[]){

        MyClass m1 = MyClass.INSTANCE; 

    }
}

Obtained output : nullWorld
Expected output : HelloWorld

In main(), if

MyClass m1 = MyClass.INSTANCE;

is replaced by

MyClass.INSTANCE.test();

then, the output is HelloWorld, as expected.

This shows that static fields are not initialized until the constructor has completed execution.

Question : How to achieve this functionality of calling a method within constructor that accesses static fields?

like image 455
Aadhirai R Avatar asked Oct 16 '22 10:10

Aadhirai R


1 Answers

This is because INSTANCE is declared before name, so it is created and initalized before name is initialized.

This works:

public enum MyClass{
    INSTANCE;
    private static final String name = "Hello";

    MyClass() {
        test();
    }

    private static void test(){
        String name1 = name + "World";
        System.out.println(name1);
    }
like image 74
Evgeniy Dorofeev Avatar answered Oct 27 '22 09:10

Evgeniy Dorofeev