Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web iThemes WordPress Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


getResponse autofunnels

Liquid Web Cloud VPS Hosting

11,407 questions

15,557 answers

573 users

How to use singleton class (can not be instantiated more than once - only one object) in Java

2 Answers

0 votes
class Singleton {  
    private static Singleton single_instance = null;  
    int n;  
      
    private Singleton() {  
        n = 837;  
    }  
      
    public static Singleton one_instance() {  
        if (single_instance == null) {  
            System.out.println("new Singleton()");  
            single_instance = new Singleton();  
        }  
        return single_instance;  
    }  
}  
public class Test   
{  
    public static void main(String args[])  
    {  
        Singleton s1 = Singleton.one_instance();  
          
        System.out.println(s1.n);  
          
        s1.n= s1.n * 2;  
          
        Singleton s2 = Singleton.one_instance();  
          
        System.out.println(s2.n); 
          
          
        Singleton s3 = Singleton.one_instance();
          
        System.out.println(s3.n); 
    }  
}    
  
   
   
   
/*
run:
   
new Singleton()
837
1674
1674
       
*/

 




answered Oct 5 by avibootz
edited Oct 5 by avibootz
0 votes
class Singleton {  
   private static Singleton single_instance = null; 
   
    public String s;
    public int n; 
   
    private Singleton() { 
        s = "Java Singleton class"; 
        n = 10;
    } 
   
    public static Singleton Singleton() { 
        if (single_instance == null) {
            System.out.println("new Singleton()");  
            single_instance = new Singleton(); 
        } 
        return single_instance; 
    } 
}  
public class Test   
{  
    public static void main(String args[])  
    {  
        Singleton s1 = Singleton.Singleton(); 
         
        System.out.println(s1.s); 
        System.out.println(s1.n);  
         
        s1.n= s1.n * 2;  
         
        Singleton s2 = Singleton.Singleton(); 
         
        System.out.println(s1.s); 
        System.out.println(s2.n); 
         
         
        Singleton s3 = Singleton.Singleton(); 
 
        System.out.println(s1.s); 
        System.out.println(s3.n); 
    }  
}    
 
  
  
  
/*
run:
  
new Singleton()
Java Singleton class
10
Java Singleton class
20
Java Singleton class
20
      
*/

 




answered Oct 5 by avibootz
edited Oct 5 by avibootz
...