Java中私有构造函数的用途是什么? [英] What's the use of private constructor in Java?

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

问题描述

我想知道私有构造函数在Java中是如何有用的.在Java中使用私有构造函数有哪些不同的方式?

I want to know that how private constructor is useful in Java. What 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.

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

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

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

制作构造函数有什么用在班上是私人的?

私有构造函数

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

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