Private
字段是从类中访问,您将无法访问他们淘汰类,例如: -
class PrivateCons{
private PrivateCons(){
System.out.println("I'm executed");
}
}
public class Test{
public static void main(String[] args) {
PrivateCons p=new PrivateCons(); //this will fail- compiler error
PrivateCons q=new PrivateCons();//this will fail- compiler error
}
}
而且私有构造函数主要用于implementing Singleton Pattern,这是用来当该类的对象只有一个是必要的。以一个例子从链接本身维基百科的文章: -
public class singleton
{
private static singleton _obj;
private singleton()
{
// prevents instantiation from external entities
}
// Instead of creating new operator, declare a method
// and that will create object and return it.
public static singleton GetObject()
{
// Check if the instance is null, then it
// will create new one and return it.
// Otherwise it will return previous one.
if (_obj == null)
{
_obj = new singleton();
}
return _obj;
}
}
您可以扩展这个例子,并限制你的对象,以2,3或任意数量的,或者换句话说restrciting你的类实例的数量。
你的主要方法是_inside_类具有私有的构造函数。所以只有你 - 作为这个类的开发者 - 有权创建它的实例,并且因此可以将它们的数量限制为你想要的数量。如果您将课堂作为图书馆的一部分提供给我,那么我不允许创建实例。这通常是提供静态工厂方法的单例或类的概念。 – Seelenvirtuose 2014-11-05 07:53:12
感谢您的解释:) – Awani 2014-11-05 08:12:46