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);
CodePudding user response:
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.
CodePudding user response:
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.