Where and how can you use a private constructor?
sobes.tech AI
Answer from AI
A private (closed) constructor is used to restrict the creation of class instances from outside. Main use cases:
-
Singleton Pattern: To ensure that a class has only one instance, the constructor is made private, and the instance is created within the class and provided through a static method.
-
Factory Methods (Factory Pattern): A private constructor allows controlling object creation through static methods, which can return different subclasses or cache objects.
-
Utility Classes: Classes with a set of static methods (e.g., java.lang.Math) make the constructor private to prevent instantiation.
-
Control of inheritance and instantiation: A private constructor can be used to prevent objects from being created directly, for example, in abstract factories.
Example of Singleton in Java:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
return instance;
}
}
Thus, a private constructor is an encapsulation tool that allows controlling object creation and ensuring certain design patterns.