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?