Like methods, we can have the private constructors in Java. To make or create a constructor as private, use the private keyword while declaring it. It can only be accessed within that class.
The following are some usage scenarios when we need a private constructor :
* Internal Constructor chaining
* Singleton class design pattern
* Below is an example of the private constructor:
PrivateConstructor.java :
class SingletonDemo {
private SingletonDemo() {
System. out.println("In a private constructor");
}
public static SingletonDemo getObject() {
// we can call this constructor
if (ref == null)
ref = new SingletonDemo();
return ref;
}
private static SingletonDemo ref;
}
public class PrivateConstructor {
public static void main(String args[]) {
SingletonDemo sObj = SingletonDemo.getObject();
}
}
Output :
In a private constructor