Syntax of Private Constructor
class clsName
{
// Variable declaration
private clsName()
{
}
// Methods
}
clsName is a valid identifier in java. It is a class name.
Example of Private Constructor
Example 1 : Program that illustrates private constructor use in java
public class SingletonObject
{
private SingletonObject()
{
// no code
}
public static SingletonObject getObject()
{
// we can call this constructor
if (ref == null)
ref = new SingletonObject();
return ref;
}
private static SingletonObject ref;
}
public class PrivateVariableDemo
{
public static void main(String args[])
{
SingletonObject sObj = SingletonObject.getSingletonObject();
}
}