私有构造函数在java中有什么用?

Raj*_*adi 0 java static constructor abstract-class

私有构造函数不允许创建对象,例如这里是代码..

class emp
{
    private emp()//private constructor
    {

    }
}

public class privateconstructor
{

    public static void main(String[] args)
    {
        emp e = new emp();//throws Error as constructor not visible

    }

}
Run Code Online (Sandbox Code Playgroud)

通过将类声明为抽象用户也可以防止创建对象.所以我的问题是为什么私有构造函数?
仅供参考:
虽然可以通过静态方法创建对象,例如..

class emp
{
    private emp()//private constructor
    {

    }
    static emp createInstance()//static method
    {
        return new emp();//returns an instance
    }

    void disp()
    {
        System.out.println("member function called");
    }
}

public class privateconstructor
{

    public static void main(String[] args)
    {
        emp e = emp.createInstance();//creating object by static method  
        e.disp();

    }

}
Run Code Online (Sandbox Code Playgroud)

output:成员函数调用

Pet*_*rey 5

所以我的问题是为什么私人建设?

这样做是为了防止从任何其他类构造类.这通常用于实用程序类,单例或具有工厂方法而不是构造函数的类.

所有enum类都有私有构造函数,它们对于Utility和Singleton类也很有用.