Singleton Class in Java
In object-oriented programming, we often need to create a class that can be instantiated only once at a time. We can’t create the object of a singleton class more than once. However, if we try to create the object of a singleton class after the first time, the new reference variable will also point to the first instance created.
All the reference variables of a singleton class object refer to the same data since they point to a similar object. To create a singleton class in Java,
- Define the class constructor as private.
- Create a static method that returns the object of this class. We will use the lazy initialization technique to evaluate the object to be created only once.
In general, we use the constructor to create the instance of the class. On the other hand, we will use the getInstance() method to get the instance of the class. Consider the following example to create the singleton class in java.
Output:
first reference: I am some other string second reference: I am some other string third reference: I am some other string
Only the first time, the value of the static variable ‘instance’ is null. Therefore, the object is created only once. The second time, the value of the variable ‘instance’ is not null, and thus, the object will not be created again, and the same object is returned.