Restrict the instantiation of class

Hi Friends

If you want to restrict the Object Creation , i.e if you want that no object should be created more than one
just go make the constructor of that class  private

Example in Java

class Sample
{
static int i=0;
Sample()
{
if(i>0)
throw new Exception("Object of this class cannot create more than One");
i++;
}
}

class Main
{
public static void main(String[] arg)
{
try
{
Sample s1=new Sample();           /*Line 1*/
Sample s2=new Sample();           /*Line 2*/
}
catch(Exception)
{
System.err.println("Object cannot create more than one");
}
}
}


Line 1 will instantiate and object and Line 2 will generate and exception.




Comments

Popular posts from this blog

How to set background color of navigation bar in iPhone