Singleton Class in Java

Singleton class helps to restrict the instantiation of the class to only one. It’s really useful in scenarios where you need only one connection, e.g. license for only one connection to database.
Now let’s see the code for Singleton Class
In the below code the default constructor is having visibility as private. The constructor can only be accessed in the same class. Now to access the constructor we created one public method which can be accessed anywhere, depending on the class visibility, and also it is marked static.

public class Singleton {
private static Singleton singleton = new Singleton( );
private Singleton() { }
public static Singleton getInstance( ) {
return singleton;
}
protected static void staticMethod( ) {
System.out.println("demoMethod for singleton");
}
}

public class SingletonDemo {
public static void main(String[] args) {
Singleton sngltn = Singleton.getInstance();
sngltn.staticMethod();
}
}