public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
public static void main(String args[]) {
Singleton s = new Singleton();
Singleton s2 = new Singleton();
}
}
Based on the "Effective Java", a singleton class is something like above.
Suppose we have a main inside this class. We can initiate the singleton class as many times as we want, like
Singleton s1=new Singleton();
Singleton s2=new Singleton();
Singleton s3=singleton.getInstance();
Singleton s4=singleton.getInstance();
A singleton class should be a class that can be only be initiated once, but the compiler will not throw a error if we declare multiple instances above, why?