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

更新於:18-06-2020

695 檢視

開啟您 職業生涯

透過完成課程獲得認證

開始
廣告