Sunday, 24 May 2020

How to create only 5 instances of a class in java

How to create only 5 instances of a class in java:

class DemoExample {   
   private static DemoExample d;
                private static int count=0;
               
   private DemoExample ()       {         
                System.out.println ("OBJECT GOT CREATED  "); 
   }    

  
   public static DemoExample create ()  {   
                                if (count<5)  {           
                                                d=new DemoExample ();           
                                                count++;
                                }           
                                else    {       
                                                System.out.println ("Cant create more than five OBJECTS");  
                                                }
                                return (d);    
  }
};
class Demomain {   
   public static void main (String [] args)       {   
         DemoExample d1=DemoExample.create ();        
                                 DemoExample d2=DemoExample.create ();       
                                 DemoExample d3=DemoExample.create ();     
                                 DemoExample d4=DemoExample.create ();       
                                 DemoExample d5=DemoExample.create ();       
                                 DemoExample d6=DemoExample.create ();       
                               
                                 }
                 };
                 
                 
                 
Above is the example code for below for which we can create five objects :
                
1) Can you give Java Code to limit the maximum creation of objects as 5?
2) Only 5 instances of a class in java?
3) Write a java class to have only five instance