Singleton class is the class which can not be instantiated more than once. To make a class singleton, we either make its constructor private or use the static getInstance method. Consider the following example.
class Singleton{
private static Singleton single_instance = null;
int i;
private Singleton ()
{
i=90;
}
public static Singleton getInstance()
{
if(single_instance == null)
{
single_instance = new Singleton();
}
return single_instance;
}
}
public class Main
{
public static void main (String args[])
{
Singleton first = Singleton.getInstance();
System.out.println("First instance integer value:"+first.i);
first.i=first.i+90;
Singleton second = Singleton.getInstance();
System.out.println("Second instance integer value:"+second.i);
}
}