Junior — Middle
Is it possible to declare a constructor as private in a class?
sobes.tech AI
Answer from AI
In Java, a constructor can be declared with any access modifier, including private. A private constructor is used, for example, in the Singleton pattern to prevent creating instances of the class from outside.
Example of a private constructor:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Thus, a private constructor restricts object creation of the class only within the class itself.