Java Private Constructor

Here you will learn about java private constructor.

What is private constructor in Java?

We can make a constructor private by using private access modifier. Private constructor prevents the instantiation of class from outside. If needed we can create the instance only inside the class.

Where to use Java private constructor?

We can use private constructor in following two situations.

1. Singleton Design Pattern

In single design pattern we have a singleton class that can have only one instance. The private constructor used in class prevents further instantiation from outside. Take below example.

2. All Static Members

If a class have all static members then there is no sense of creating an object because the members can be accessed by class name. In that case we can write a private constructor inside class to prevent object creation.

Comment below if you have doubts or found any information incorrect in above tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *