Singleton Class Using Private Constructor Java Example Program


Syntax

class ClassName
{
    static ClassName instance = null;
   
    private ClassName() {  }
  
    static public ClassName getInstance()
    {
        if (instance == null)        
             instance = new Singleton();
  
        return instance;
    } 
}

//Usage
ClassName instance = ClassName.getInstance();

Singleton Class Example Program

class Singleton
{
    static Singleton instance = null;
    public int instanceValue = 10;
   
    private Singleton() {  }
  
    static public Singleton getInstance()
    {
        if (instance == null)        
             instance = new Singleton();
  
        return instance;
    } 
}

public class SingletonClass {
    public static void main(String args[])    
   {
       Singleton instance1 = Singleton.getInstance();
       Singleton instance2 = Singleton.getInstance();
       
       //Objects are different
       //But same instance will be used
       instance1.instanceValue = instance1.instanceValue + 10;
       System.out.println("Value of instance1.instanceValue = " + instance1.instanceValue);
       System.out.println("Value of instance2.instanceValue = " + instance2.instanceValue);
   }    
}

Sample Output

Value of instance1.instanceValue = 20
Value of instance2.instanceValue = 20