私有构造不允许创建例如对象这里是代码..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
}
}
通过声明类为抽象用户还可以防止创建的对象..所以我的问题是,为什么私有构造?
只为信息:
虽然对象可以通过例如静态方法创建..
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();
}
}
输出:成员函数调用
它确保你没有人能够创建一个新的实例(除非那个人知道反射),当你想要一个类的一个实例,比如Singleton模式时,它很有用。 – 2013-07-14 20:31:13