mardi 17 juillet 2018

Java static object scope in singleton design pattern not throwing null pointer exception

I have created a class as below while practicing singleton pattern :-

class Singleton
{
    // static variable single_instance of type Singleton
    private static final Singleton single_instance = new Singleton();

    // private constructor restricted to this class itself
    private Singleton()
    {
        System.out.println("Yahoo");
    }

    // static method to create instance of Singleton class
    public static Singleton getInstance()
    {
        return single_instance;
    }
    public static void getDemo()
    {
        System.out.println("YOHOO");
    }
}

I know its not entirely correct. But then in the main class, in the main function I called this way :-

package common;

public class TestMain {

    public static void main(String[] args) {
        Singleton tmp = Singleton.getInstance();
        tmp = null;
        System.out.println(tmp);
        tmp.getDemo();

    }

}

And what prints is this :-

Yahoo
null
YOHOO

But why not a null pointer exception when calling getDemo() the second time? I am not sure if I am missing any scope details but would appreciate the help.

Aucun commentaire:

Enregistrer un commentaire