Java – why can I unexpectedly create multiple instances of my singleton class?

According to my knowledge, singleton design pattern means that we can only create a single object of one class

The following code runs successfully without any errors / exceptions

I want the code to fail because the singletonexample class has a private default constructor

public class SingletonExample {
    private static SingletonExample singletonInstance;

    private SingletonExample() {
    }

    public static SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
            System.out.println("Creating new instance");
            singletonInstance = new SingletonExample();
        }
        return singletonInstance;
    }

    public void printSingleton(){
        System.out.println("Inside print Singleton");
    }

    public static void main(String a[])  {
        SingletonExample singObj1 = new SingletonExample();
        SingletonExample singObj2 = new SingletonExample();
    }
}

Is there a problem with my code?

Solution

Because your main method is in the class singletonexample, the main code can access the private constructor

Try moving the main method to another class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>