Yes , Constructors can have any access specifier/access modifier.
Private constructors are useful for creating singleton
classes.
Singleton - A singleton class is a class where only a single object can be created at runtime (per JVM) .
A simple example of a singleton class is -
class Ex {
private static Ex instance;
int a;
private Ex() {
a = 10;
}
public static Ex getInstance() {
if(instance == null) {
instance = new Ex();
}
return instance;
}
}
Note, for the above class, the only way to get an object (outside this class) is to call the getInstance() function, which would only create a single instance and keep returning that.
Also, note that this is not thread-safe.