Nov 10, 2018

Private constructor in Java

Private constructor = only the native class is allowed to create an instance of the class.

2 purposes:
  1. you don’t want any objects of your class to be created at all, such as for classes that only have static members.
  2. you only want objects to be created internally, only in your class. For example, in singleton pattern.
Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the creation of that default constructor.