私有构造函数不允许创建对象,例如这里是代码..
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)