Limit the Class Object Creation

In this section you will learn about how a class object creation can be a restricted to a fix number of times.

Limit the Class Object Creation

In this section you will learn about how a class object creation can be a restricted to a fix number of times.

Limit the Class Object Creation

Limit the Class Object Creation

In this section you will learn about how a class object creation can be a restricted to a fix number of times.

In this tutorial I am giving a sample code which will demonstrate you about how to restrict the object creation of a class. This is a simple code in Java where I have created a class named ClassInstance which contains the two static data members named ci and counter. The data member ci is of ClassInstance type and the other is the counter used to count the number of times the object created. Besides these this class contained getClassInstance() and main() methods. The getClassInstance() method returns the class object. and in the main method I have created the objects of this class and added them into a list and traversed this list.

Sample Codes

ClassInstance.java

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public final class ClassInstance {

private static ClassInstance ci;
private static int counter=0;

private ClassInstance() {
counter++; 
}
public static ClassInstance getClassInstance() {
if(counter<5)
{
ci = new ClassInstance();
}
else if(counter >=5)
{
ci = new ClassInstance();
ci=null; 
} 
return ci;
}

public static void main(String[] args)
{
try{

List<ClassInstance> list = new ArrayList<ClassInstance>();
ClassInstance obj1 = ClassInstance.getClassInstance();
ClassInstance obj2 = ClassInstance.getClassInstance();
ClassInstance obj3 = ClassInstance.getClassInstance();
ClassInstance obj4 = ClassInstance.getClassInstance();
ClassInstance obj5 = ClassInstance.getClassInstance();
ClassInstance obj6 = ClassInstance.getClassInstance();
ClassInstance obj7 = ClassInstance.getClassInstance();
ClassInstance obj8 = ClassInstance.getClassInstance();
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
list.add(obj5);
list.add(obj6);
list.add(obj7);
list.add(obj8);
ListIterator<ClassInstance> itr = list.listIterator();
while(itr.hasNext())
{ 
System.out.println(itr.next().hashCode()); 
}
}
catch(Exception e)
{
try
{
if(counter >= 5)
{
MyException.counter = counter;
}
throw new MyException();
}
catch(MyException e1)
{
System.out.println("Exception@ "+ClassInstance.class+" : "+e1);
}
}
}
}

MyException.java

public class MyException extends Exception{

static String msg = "";
static int counter ;
public MyException(){
super(msg);
}
public MyException(String str){
super(str);
}
public String toString()
{
if (counter >= 5)
msg = "Object creation exceeded the limit Only 5 times object creation is allowed";
return msg;
}
}

Output

I have made this example using Eclipse IDE so the output is in its perspective.

Download Source Code