Java中私有构造函数的目的是什么?
在限制对象创建时,私有构造函数很有用。例如,单例模式可以使用私有构造函数实现。
示例
public class Tester {
private static Tester instance;
private Tester(){}
public static Tester getInstance(){
if(instance == null){
instance = new Tester();
}
return instance;
}
public static void main(String[] args) {
Tester tester = Tester.getInstance();
Tester tester1 = Tester.getInstance();
System.out.println(tester.equals(tester1));
}
}输出
它将打印输出为
true
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP