簡體   English   中英

如何在Java中創建class LocalDate的object? 為什么不使用 new 關鍵字?

[英]How to create the object of class LocalDate in Java? And why not use new keyword?

I am using this code to create the object of class LocalDate in Java.time package but it does not require the keyword new . 誰能告訴我這到底是如何工作的。

LocalDate date = LocalDate.of(year, month, day);

LocalDate 提供了一個名為of static 方法,用於分配一個新實例。

任何 class 都可以做到這一點。

    class MyClass {
          :
       static MyClass makeOne(int someArg) {
           :
          MyClass thing = new MyClass();
           :
          return thing;
       }
        :
     }
       

如果有意義of話, makeOne可能同樣會被命名。

所以,你是對的,'new' 是創建實例的方式,但這並不意味着'new' 調用是寫在你的代碼中的。

LocalDate class 有一個私有構造函數。 因此,您不能使用 new 關鍵字實例化LocalDate class 的新實例。 But the LocalDate class implements a static function of , which lets you specify the year, month, and day of the month, and the function returns the new constructed LocalDate object.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM