I know the concept of singleton in Java. I'm having problems with creating singleton as inner class in Java. Problem occurs at holder's
public class NormalClass {
private class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private static class SingletonHolder {
private static Singleton sessionData = new Singleton();
}
public static Singleton getInstance() {
return NormalClass.Singleton.SingletonHolder.sessionData;
}
}
public void method1() {
Singleton.getInstance();
}
}
Error is at new Singleton() constructor call. How to proper call private constructor of Singleton as inner class?
Regards
If it should be a real singleton, make your singleton class static. Then you will be able to call the constructor.
The reason why your constructor call does not work is explained in the Java nested classes tutorial. Basically, the inner class requires an instance of the outer class before it can be constructed:
private static Singleton sessionData = new NormalClass().new Singleton();
You cannot declare static classes within a non-static class. Make the Singleton
class static and everything should compile just fine.
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