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