Friday, 6 January 2017

Singleton vs Static class in Java

What is Static class in Java? What is singleton class? How are they different?

Static class is a Java class, which only contains static methods.
Ex: java.lang.Math

Which contains lots of utility methods for various Maths function e.g. sqrt(). No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.

Singleton classes are those, which has only one instance during application lifecycle. And usually, have a private constructor and one static method to create the instance.

Ex: like java.lang.Runtime

Singleton Class is the class of which only single instance can exist per classloader.

Some important Points:

Singleton class
Static class
Singleton can extend classes and implement interfaces
While a static class cannot (it can extend classes, but it does not inherit their instance, members).
A singleton can be initialized lazily or asynchronously
While a static class is generally initialized when it is first loaded, leading to potential class loader issues.


Static class provides better performance than Singleton pattern because static methods are bonded at compile time.
One difference between Singleton and static is the ability to override. You can override methods defined in Singleton class by extending it.
Since static methods in Java cannot be overridden, they lead to inflexibility.
If your requirements need to maintain state than Singleton pattern is a better choice than static class because maintaining state in the later case is a nightmare and leads to subtle bugs.


Singleton classes can be lazy loaded if it is a heavy object, but static class doesn't have such advantages and always eagerly loaded.

Many Dependency Injection frameworks manage Singleton quite well e.g. Spring, which makes using them very easy.


The main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime a static class, it’s not possible to return different implementation for different JVM.

Singleton class follow the OOP(object oriented principles) but not a static class. We can implement an interface with Singleton class but not with Static class.
Singleton object stored in Heap.
However static object stores in the stack.
We can clone the object of Singleton.
We cannot clone the static class(=clone is possible only of instance).


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...