Strange behaviour of singleton

I assign the reference of singleton object to null.

But still it is calling method of the Singleton class.

Here is my code

class Singleton {

private static Singleton singleton = new Singleton();

/*
 * A private Constructor prevents any other class from instantiating.
 */
private Singleton() {
}

/* Static 'instance' method */
public static Singleton getInstance() {
    return singleton;
}

/* Other methods protected by singleton-ness */
protected static void demoMethod() {
    System.out.println("demoMethod for singleton");
}
}

public class SingletonDemo {
    public static void main(String[] args) {
        Singleton tmp = Singleton.getInstance();
        tmp.demoMethod();
        tmp = null;
        tmp.demoMethod();

    }
}

enter image description here

Jon Skeet
people
quotationmark

You're calling demoMethod, which is a static method - so your code here:

tmp.demoMethod();

is actually being compiled to:

Singleton.demoMethod();

That clearly doesn't depend on the value of tmp.

This has absolutely nothing to do with being the singleton aspect:

public class Test {
    public static void main(String[] args) {
        String x = null;
        System.out.println(x.valueOf(10)); // Calls String.valueOf(10)
    }
}

Note that Eclipse has put yellow squiggly lines under those method calls - I strongly suspect if you look at the warnings, you'll see it telling you not to call static methods like this. Follow the advice, and you won't get odd behaviour...

people

See more on this question at Stackoverflow