我在很多网站上都读到了私有(private)构造函数,也在 StackOverflow 上提到了各种问题。但是,我未能理解它们的用法。大多数网站都说当我们想限制可以创建的对象实例的数量时可以使用私有(private)构造函数。
我尝试了以下程序:
public class PrivateCons{
private PrivateCons(){
System.out.println("I'm executed");
}
public static void main(String[] args) {
PrivateCons p=new PrivateCons();
PrivateCons q=new PrivateCons();
}
}
我的程序执行得非常好。我是不是理解错了这个概念?
最佳答案
私有(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
}
}
此外,私有(private)构造函数主要用于 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 或任何数字,或者换句话说,限制您的类的实例数。
关于java - 使用私有(private)构造函数创建类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26752021/