Instanciate your class via a factory (see design patterns) and limit it to 3 instances using a simple counter.
public class LimitClass {
private static LimitClass limInstance;
public static int objCount = 0;
private LimitClass(){
objCount++;
}
public static synchronized LimitClass getLimInstance(){
if(objCount < 3 ){
limInstance = new LimitClass();
}
return limInstance;
}
}
public class LimitObjectCreationTest {
public static void main(String[] args) {
LimitClass obj1 = LimitClass.getLimInstance();
LimitClass obj2 = LimitClass.getLimInstance();
LimitClass obj3 = LimitClass.getLimInstance();
LimitClass obj4 = LimitClass.getLimInstance();
LimitClass obj5 = LimitClass.getLimInstance();
LimitClass obj6 = LimitClass.getLimInstance();
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);
System.out.println(obj4);
System.out.println(obj5);
System.out.println(obj6);
}
}
Output of above code is like:
com.pack2.LimitClass@19821f com.pack2.LimitClass@addbf1 com.pack2.LimitClass@42e816 com.pack2.LimitClass@42e816 com.pack2.LimitClass@42e816 com.pack2.LimitClass@42e816