Junior — Middle
Can you give an example of a class with a private constructor and explain its purpose?
sobes.tech AI
Answer from AI
An example of a class with a private constructor is a singleton. A private constructor prevents creating instances of the class from outside, ensuring control over object creation.
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The purpose of a private constructor is to restrict the creation of class objects, for example, to guarantee that only one instance exists (Singleton pattern) or to ensure the class is used only statically (e.g., utility class).