Computer >> Computer tutorials >  >> Programming >> Java

How to make a class singleton in Java?


A Singleton class is a class that has only a single object., which means that we can instantiate the class only once. When we declare the constructor of the class as private, it will limit the scope of the creation of the object. If we return an instance of the object to a static method, we can handle the object creation inside the class itself. We can create a static block for the creation of an object.

Example

public class SingletonClassTest {
   private static SingletonClassTest obj;
   static {
      obj = new SingletonClassTest(); // creation of object in a static block
   }
   private SingletonClassTest() { } // declaring the constructor as private
   public static SingletonClassTest getObject() {
      return obj;
   }
   public void print() {
      System.out.println("Singlton Class Test");
   }
   public static void main(String[] args) {
      SingletonClassTest test = getObject();
      test.print();
   }
}

Output

Singlton Class Test