Private Constructor in java

It is very important point to know as a java developer. So normally constructor is a special method which is used to initialize the instance variables.we can apply public,protected,default,private modifiers to constructors.so here our question is what happens if apply private modifier to constructor the answer is ,if we apply private to constructor the object creation is not possible out side of the class.the object creation is possible only internally with in the class.

In some cases we will use private costructor
  • sigleton
  • static methods(utililty methods)
  • factory methods
Our main point is using private constructor we can restrict object creation out side of the class.
As we know we can use private constructor is used to create singleton class see the below
Example
package com.java2study;
 public class PrivateConstructorDemo {
 private static PrivateConstructorDemo p;
 private PrivateConstructorDemo() {
  super();
 System.out.println("private constructor"); 
 }
 public static PrivateConstructorDemo getInstace(){
  if(p == null){
   p = new PrivateConstructorDemo();
  }
  return p;
 }
}
package com.java2study;

public class Test {

 
 public static void main(String[] args) {
  PrivateConstructorDemo p1 = PrivateConstructorDemo.getInstace();
  PrivateConstructorDemo p2 = PrivateConstructorDemo.getInstace();
  PrivateConstructorDemo p3 = PrivateConstructorDemo.getInstace();
  System.out.println(p1.hashCode());
  System.out.println(p2.hashCode());
  System.out.println(p3.hashCode());
  System.out.println(p1.hashCode() == p2.hashCode());
  System.out.println(p2.hashCode() == p3.hashCode());
  System.out.println(p1.hashCode() == p3.hashCode());

 }

}
output
private constructor
640642021
640642021
640642021
true
true
true