私有构造函数在java中有什么用处 [英] What is the use of private constructor in java

查看:112
本文介绍了私有构造函数在java中有什么用处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道私有构造函数在java中的用处。
这是在java中使用私有构造函数的不同方法。

I want to know that, how private constructor is useful in java. which are the different ways to use private constructor in java.

推荐答案

私有构造函数当然不能限制类的实例化。

private constructor is off course to restrict instantiation of the class.

实际上,私有构造函数的好用是Singleton Pattern。这是一个例子

Actually a good use of private constructor is in Singleton Pattern. here's an example

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}

这样你可以确保只有一个类的实例是活动的。

this way you can ensure that only one instance of class is active.

其他用途可以是创建实用程序类,它只包含静态方法。

Other uses can be to create a utility class, that only contains static methods.

对于更多分析,您可以查看其他堆栈溢出答案

For, more analysis you can look into other Stack overflow answers

Java中的构造函数可以是私有的吗?

< a href =https://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class>在类中创建私有构造函数有什么用? ?

私人构造函数

这篇关于私有构造函数在java中有什么用处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆