Private Constructors and Singleton Classes in Java Programming

Java 8Object Oriented ProgrammingProgramming

As we know the primary role of the constructor is to instantiate a class object now if we made the constructor as private then we restrict its calling to be only in defining a class and not in some other class.

Now the singleton class in Java is defined as the class which restricts the instantiation of a class and ensure that only one instance of the class exists in the JVM. After first time if instantiate the singleton class the new variable also points to the first instance created.

In order to create a singleton class we could use the concept of the private constructor as it also restricts the instantiation of class in defining class only. In singleton class, we use private constructor so that any target class could not instantiate our class directly by calling constructor, however, the object of our singleton class is provided to the target class by calling a static method in which the logic to provide only one object of singleton class is written/defined.

The designing of a singleton class is better explained by the following example.

Example

Live Demo

public class SingletonClassDriver {
   public static void main(String[] args) {
   
      SingletonClass obj = SingletonClass.getObject();
      SingletonClass obj1 = SingletonClass.getObject();
      System.out.println(obj);
      System.out.println(obj1);
   }
}
class SingletonClass {
   public static SingletonClass obj = null;
      private SingletonClass() {
   }
   public static SingletonClass getObject() {
      if (obj == null) {
         obj = new SingletonClass();
      }
      return obj;
   }
}

Output

SingletonClass@f6a746
SingletonClass@f6a746
raja
Published on 03-Dec-2018 11:39:51
Advertisements