What’s the use of private constructor in Java?

private constructor is off course to restrict instantiation of the class.

Actually a good use of private constructor is in Singleton Pattern. here’s an example

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}

this way you can ensure that only one instance of class is active.

Other uses can be to create a utility class, that only contains static methods.

For, more analysis you can look into other Stack overflow answers

Can a constructor in Java be private?

What is the use of making constructor private in a class?

private constructor

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)