What is the purpose of private constructor in Java?

Java Programming Java8Object Oriented Programming

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
raja
Published on 23-Apr-2018 11:01:49
Advertisements