Private constructor

  • The private constructor is used in singleton classes.
  • A Singleton class is used to create an instance only one for that class.
  • A private constructor used to prevent the creation of more than one object for the class.


Example program:
package com.javatutorial;

public class SingleTonEx {
    
    public static void main(String[] args) {
        
        SingleTonClass obj1 = new SingleTonClass(); //Compiler error because of private constractor (The constructor SingleTonClass() is not visible)
        obj1.display();
        
        SingleTonClass obj2 = SingleTonClass.getInstance();
        obj2.display();

    }

}

class SingleTonClass{

    private static SingleTonClass obj;
    
    //Here private constractor avoid to create object for this class
    private SingleTonClass()
    {        
    }
    
    //Create a instance only once for this class
    public static SingleTonClass getInstance()
    {
        if(obj == null)
        {
            obj = new SingleTonClass();
        }
        return obj;
    }
    
    public void display()
    {
        System.out.println("display method");
    }
}




Comments

Popular posts from this blog

Google Assistant Implementation in Android application with app actions