Why to have a private constructor


Constructors are meant to be public.

Why should we make them private?

Let's check the cases where we should consider creating private constructor

Case 1: For Singleton design pattern

A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor.

Case 2: When creating an object doesn't make sense

This occurs when :
  1. the class only contains static members, those members can be accessed using only the class name 
  2. no instance of the class needs to be created

Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the usage of that default constructor, thereby preventing a caller from creating an instance of the class.

Note that the private constructor can be empty.


Previous Post Next Post