Singleton class in java – Includes Easy Implementation Steps

(Last Updated On: April 9, 2018)

Learn singleton class in java with example. Singleton class is just a concept and we can make any class singleton which we want by following some rules. Singleton class restricts the instantiation of a class to single instance and ensures that only one instance of the class exists in the application. Users e.g. other classes and methods cannot create the object of singleton class. only class itself creates an object and provide a public static method to users to get the object. It is also known as singleton design pattern.

Once you understand singleton, you can read real time examples of singleton design pattern in java, means where and why you should use singleton class in java programs.


How to create singleton class in java

Here are some easy steps to make a class singleton with singleton class example program

Step -1: First we need to make a constructor of the class private so that object of the class cannot be created outside of the class.

Step -2: Create a private static object of the class itself as member field. It should be static because we will be using it in a static method that can access only static field.

Step -3: Create a static method e.g. getInstance() and return the object field created in the class itself. This method will be static so object can be called from outside of the class using class name, as user class or method cannot create an object. The object can be accessed by getInstance() method.

Example of Singleton class in Java

In this example of singleton class, the Car class has been made as Singleton and demonstrated the object calls in main () program.

Car running….
Car running….
Car running….

Notice that constructor has been called only a single time while we have called object 3 times in main function. Meaning, only a single object has been created of the class and the same singleton class object is getting called again and again using getInstance() method of Car singleton class in Java program.