Limiting the number of objects created in JAVA

Q   :- How can you limit the number of objects created in java ?

Sol :- In the example below MyClass constructor has been used to limit the  number of objects that can be created to 2 by using a count which has been declared static(single copy for all objects of a class).If one tries to create more than 2 objects the constructor will throw an error. 

class LimitInstanceOfObject
{
public static void main(String [] args) throws Exception
{
MyClass obj1,obj2,obj3,obj4;
try
{
obj1=new MyClass();
obj2=new MyClass();
obj1.fun();
obj2.fun();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
try
{
obj3=new MyClass();
obj4=new MyClass();
obj3.fun();
obj4.fun();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

class MyClass
{
public static int count=0;
public MyClass() throws Exception
{
if(MyClass.count==2)
throw new Exception("Object creation limit exceeded !");
else
count++;
System.out.println("count = "+count);
}
public void fun()
{
System.out.println("Lolzzzzzz");
}

}

Comments

Popular posts from this blog

AGRICULTURAL SCIENTIST RECRUITMENT BOARD

HSC Exam Time Table 2013 Arts, Commerce, Science

What are cookies and its types? Where are cookies used?