Limit the number of objects being created in JAVA

Q   :- Limit the number of objects being created in JAVA.

Sol :- The example below limits creation of objects of MyClass class to a maximum of 5 by declaring the constructor private and calling it via getMyClass() method.If an attempt to create more than 5 objects is done, the getMyClass() method will return a null,thus,the object so created will not be referenced and ultimately cleared by the garbage collector.
 
import java.io.*;
class MyClass
{
public static int count=0;
int a;
private MyClass()
{
count++;
a=count;
System.out.println("object created  = "+a);
if(count>4)
System.out.println("Object Creation Limit Exceeded");
}
public static MyClass getMyClass()
{
if(MyClass.count==5)
return null;
else
return new MyClass();
}
}

class LimitObjectInstance
{
public static void main(String [] args)
{
int i=-1,ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
MyClass obj[]=new MyClass[10];
while(true)
{
System.out.println("\nDo you want to create new Object (1 for Yes ) ??   ");
try
{
ch=Integer.parseInt(br.readLine()) ;
}
catch(Exception e)
{
ch=2;
}
if(ch==1)
{
i++;
                   obj[i]= MyClass.getMyClass();
}
else
{
System.exit(0);
}
}
}
}

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?