Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java singleton inner class

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

like image 212
zmeda Avatar asked Dec 28 '22 07:12

zmeda


2 Answers

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();
like image 110
Robin Avatar answered Jan 12 '23 07:01

Robin


You cannot declare static classes within a non-static class. Make the Singleton class static and everything should compile just fine.

like image 40
janhink Avatar answered Jan 12 '23 08:01

janhink