Private Constructor in Java

In Java, the constructor is a special type of method that has the same name as the class name. Internally, a constructor is always called when we create an object of the class. It is used to initialize the state of an object.

In the same way, Java also allows us to create a private constructor. In this section, we will discuss private constructors in Java, rules for creating a private constructor, and its use cases. Also, we will see its implementation.

What is a private constructor?

Java allows us to declare a constructor as private. We can declare a constructor private by using the private access specifier. Note that if a constructor is declared private, we are not able to create an object of the class. Instead, we can use this private constructor in Singleton Design Pattern.

Rules for Private Constructor

The following rules keep in mind while dealing with private constructors.

  • It does not allow a class to be sub-classed.
  • It does not allow to create an object outside the class.
  • If a class has a private constructor and when we try to extend the class, a compile-time error occurs.
  • We cannot access a private constructor from any other class.
  • If all the constant methods are there in our class, we can use a private constructor.
  • If all the methods are static then we can use a private constructor.
  • We can use a public function to call the private constructor if an object is not initialized.
  • We can return only the instance of that object if an object is already initialized.

Use Cases of Private Constructor

The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern. The use-cases of the private constructor are as follows:

  • It can be used with static members-only classes.
  • It can be used with static utilityor constant classes.
  • It can also be used to create singleton classes.
  • It can be used to assign a name, for instance, creation by utilizing factory methods.
  • It is also used to avoid sub-classing.
  • It incorporates the factory methods.

Let's see the implementation of the private constructor.

Implementation of a Private Constructor

A.java

Output:

Private Constructor in Java

PrivateConstructorDemo.java

Output:

true