java - 使用私有(private)构造函数创建类的对象

标签 java constructor

我在很多网站上都读到了私有(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/

相关文章:

java - TitanDB 删除所有内容,包括索引

java - 如何在removeKeyListener之后使用addKeyListener?

c++ - 使用另一个类的构造函数

syntax - Kotlin 二级构造函数

c++ - 避免使用虚方法构造具有空基类的构造函数

Java Stream按一个属性分组并按另一个属性收集最大元素

java - 如何将 photoview 或 Imageview 放入 viewpager android

java - 如何将变量从 jtextfield 传递到另一个 JFrame/类中的另一个 jtextfield?

java - 根据输入长度调用正确的构造函数

java - Selenium WebDriver - Java - 更改用户代理