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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With