When to use Static Class in Place of Singleton in Java

Static Class in Java

We can’t make top level classes in Java as static. Only nested classes can be static.

/* Java program to demonstrate how to implement static in a java program. */
class OuterClass{
   private static String msg = "SomeRandomMessage";

   // Static nested class
   public static class NestedStaticClass{

       // Only static members of Outer class is directly accessible in nested 
       // static class 
       public void printMessage() {

         // Try making 'message' a non-static variable, there will be 
         // compiler error  
         System.out.println("Message from nested static class: " + msg); 
       }
    }
} 

And here’s how the NestedStaticClass can be used.

class Main
{
    // How to create instance of static and non static nested class?
    public static void main(String args[]){

       // create instance of nested Static class
       OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();

       // call non static method of nested static class
       printer.printMessage();   
    }
}

Static classes are useful when:
– you just need to provide global access to methods without maintaining any state.
– static classes are much faster than Singleton, because of static binding during compile time
– if you need to combine a bunch of utility methods together then static methods can be used.

Singleton Class in Java

Ensure a class has only one instance, and provide a global point of access to it. The Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private.

public class SingletonExample {
    // Static member holds only one instance of the
    // SingletonExample class
    private static SingletonExample singletonInstance;

    // SingletonExample prevents any other class from instantiating
    private SingletonExample() {
    }

    // Providing Global point of access
    public static SingletonExample getSingletonInstance() {
        if (null == singletonInstance) {
        singletonInstance = new SingletonExample();
        }
        return singletonInstance;
    }
}

Advantages of using singleton classes over static classes:
– a singleton can extend classes and implement interfaces
– a singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded
– singletons can be handled polymorphically without forcing their users to assume that there is only one instance

This content has been helpful to you?

Thanks for contributing!

Yes No