class Singleton{
private static Singleton singletonObject;
private static int single;
/** A private Constructor prevents any other class from instantiating. */
private Singleton(){
// Optional Code
single++;
System.out.println(“Singleton Zero ARGS Constructor:”+single);
}
public static synchronized Singleton getSingletonObject()
{
if (singletonObject == null){
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone()throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}
public class SingletonObjectDemo {
public static void main(String args[]){
// Singleton obj = new Singleton(); Compilation error not allowed
//create the Singleton Object..
Singleton obj = Singleton.getSingletonObject();
//create a copy of the Object by cloning it using the Object’s clone method
// Since its overrided
// SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
// Second instance will not invoke constructor since already object is created.
System.out.println(“Singleton object obtained”);
Singleton obj2 = Singleton.getSingletonObject();
}
}