Singleton Class in Java

Developer Helps
developerhelps
Published in
2 min readAug 23, 2020

Singleton class in java is a class that can have only a single object. It also means it can have just one instance of a class at the same time. In java, even when we try to make another object from the singleton class. It will only point towards the earlier created instance. So any changes in the class, they will only reflect upon the single created instance of that class. The singleton class has the power to control the instantiation of the class, therefore they also have the flexibility that it can change the whole process of creating an instance.

We need to make some modifications to make a class singleton.

  • By making the singleton class private.
  • We write a static method that can only return an object of singleton type. We can do this by delaying the creation of an object, this process is also called as lazy initialization. The process will enhance the performance as the dependency on the creation of an object is only handled when it is needed.
  • It needs to provide a global access point to get the instance of a class i.e. object.
  • We also create a private attribute that points towards the singleton object of the class.

Java Program on Singleton Class

public class MySingleton {
private static MySingleton Obj;
static{
Obj = new MySingleton();
}
private MySingleton(){
}
public static MySingleton getInstance(){
return Obj;
}
public void testMe(){
System.out.println("Welcome to Developer Helps !!");
}
public static void main(String a[]){
MySingleton ms = getInstance();
ms.testMe();
}
}

The output of the following program will be:

Welcome to Developer Helps !!

Read More: Singleton Class in Java

More Examples

Collections in Java
Logical operators in Java with Example [2020]

--

--

Developer Helps
developerhelps

Developer Helps will provides to you latest Tutorials regarding PHP, MySQL and much more.