I want to know that how private constructor is useful in Java. What are the different ways to use private constructor in Java?
Design Pattern of Singleton classes: The constructor of singleton class would be private so there must be another way to get the instance of that class. This problem is resolved using a class member instance and a factory method to return the class member. // pattern using private constructors.
In singleton class, we use private constructor so that any target class could not instantiate our class directly by calling constructor, however, the object of our singleton class is provided to the target class by calling a static method in which the logic to provide only one object of singleton class is written/ ...
Class. getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
private constructor is off course to restrict instantiation of the class.
Actually a good use of private constructor is in Singleton Pattern. here's an example
public class ClassicSingleton { private static ClassicSingleton instance = null; private ClassicSingleton() { // Exists only to defeat instantiation. } public static ClassicSingleton getInstance() { if(instance == null) { instance = new ClassicSingleton(); } return instance; } }
this way you can ensure that only one instance of class is active.
Other uses can be to create a utility class, that only contains static methods.
For, more analysis you can look into other Stack overflow answers
Can a constructor in Java be private?
What is the use of making constructor private in a class?
private constructor
As other answers mentioned, common uses include the singleton pattern, internal constructor chaining and one more:
Java doesn't support what in C# (for example) is known as a "static class" - in other words, a utility class. A utility class is a helper class that's supposed to contain only static members. (Math
and System
are such cases in Java.) It doesn't make sense for them to be instantiated in any way.
In C#, making a class static makes it implicitly both final/sealed and abstract. In Java, there is no such keyword and you can't make a class final and abstract. So if you had such a utility class, you'd make it final and give it a private constructor that's never called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With