I have code like this:
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
System.out.println("Singleton constructed.");
}
public static Singleton getInstance() {
return INSTANCE;
}
}
When we don't have any other static method that getInstance, is this singleton lazy initializated? As far as I know class is initialized only in some cases, like:
- An Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
- An static method of Class is invoked.
- An static field of Class is assigned.
- An static field of class is used which is not a constant variable.
- If Class is a top level class and an assert statement lexically nested within class is executed.
So when the only static method is getInstance
and constructor is private there is no possibility to initialize Singleton class in any other way than using getInstance method (apart from reflection). So the object is created only when we need it so it's a lazy initialization, right? Or maybe I missed something?