小编Raj*_*adi的帖子

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

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

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 …
Run Code Online (Sandbox Code Playgroud)

java static constructor abstract-class

0
推荐指数
1
解决办法
566
查看次数

标签 统计

abstract-class ×1

constructor ×1

java ×1

static ×1