Difference between singleton class and static class?

java, singleton, static

Solution

Singleton Class: Singleton Class is class of which only single instance can exists per classloader.

Static/Helper Class (Class with only static fields/methods): No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.

Following is referenced from this blog "Static classes in Java" describes it nicely. The blog also has examples for explaining same:

Singleton example:

public class ClassicSingleton {
    private static ClassicSingleton instance = null;

    private ClassicSingleton() {
        // Exists only to defeat instantiation.
    }

    public static ClassicSingleton getInstance() {
        if (instance == null) {
            instance = new ClassicSingleton();
        }
        return instance;
    }
}

Static Class example:

/**
 * A helper class with useful static utility functions.
 */
public final class ActionHelper {

    /**
     * private constructor to stop people instantiating it.
     */
    private ActionHelper() {
        // this is never run
    }

    /**
     * prints hello world and then the users name
     * 
     * @param users
     *            name
     */
    public static void printHelloWorld(final String name) {
        System.out.println("Hello World its " + name);
    }

}

So what's the difference between the two examples and why do I think the second solution is better for a class you don't want or need to instantiate. Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.

Same answer is also referenced from my answer here

Problem

Possible Duplicates: Difference between static class and singleton pattern? What is the difference between a Singleton pattern and a static class in Java? HI I am not clearly getting What’s the difference between a singleton class and a static class? Can anybody elaborate this with example?

Original source

Related problems