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

Your build is currently configured to use incompatible Java 21.0.3 and Gradle 8.2.1. Cannot sync the project.

SonarQube With Angular 19 on Windows: A Complete Setup and Integration Guide

Error in Android Migration Gradle 7.5 to 8.5 - java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null