简体   繁体   中英

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 . Can anyone tell me how this exactly works.

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

LocalDate provides a static method named of that allocates a new instance.

Any class can do this.

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

makeOne might equally be named of if that makes sense.

So, you're right, 'new' is how instances get created, but that doesn't mean the 'new' call is written in your code.

The LocalDate class has a private constructor. So you cannot instantiate a new instance of the LocalDate class using the new keyword. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM