Skip to main content

Posts

Showing posts with the label program

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 InputStream...

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 !"); el...