Sunday, April 5, 2015

What’s the point of having a private constructor in Java?

There are two possible reasons why one would want to use a private constructor – the first is that you don’t want any objects of a class to be created at all, and the second is that we want objects to be created internally – as in only created in our class.

Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so.

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

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 may even be empty.

No comments: