What is the purpose of private constructor in Java?


The private constructor is useful in case we want to restrict the object creation. For example, Singleton pattern can be implemented using a private constructor.

Example

Live Demo

public class Tester {
   private static Tester instance;
   private Tester(){}
 
   public static Tester getInstance(){
      if(instance == null){
         instance = new Tester();
      }
      return instance;
   }
 
   public static void main(String[] args) {
      Tester tester = Tester.getInstance();
      Tester tester1 = Tester.getInstance();
      System.out.println(tester.equals(tester1));
   }  
}

Output

It will print the output as

true

Updated on: 18-Jun-2020

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements