Reputation: 131
I'm reviewing Java 8 classes of the Time package and I have a doubt about the classes without constructor like LocalDate class.
If you create a Java class, this class will always have a default constructor, nevertheless LocalDate hasn't constructor, that is to say, you can't do this:
LocalDate date = new LocalDate();
If you do this, you will get a compile error "the constructor LocalDate() is undefined".
Why LocalDate hasn't a default constructor?
And the most important question... How can I create a class without constructor that only can be instanced calling static methods?
Thank you very much and regards.
Upvotes: 11
Views: 17580
Reputation: 140494
Why LocalDate hasn't a default constructor?
Because there is no "default value" for it to construct which makes sense. What would the year, month and day fields' values be in this case?
The default constructor is not the same thing as an explicit constructor with zero arguments. The default constructor is something added by the compiler, but only if you define no other constructors (language spec). LocalDate
has an explicit constructor, and thus it has no default constructor. That constructor is also private, so you can't invoke it directly.
Effective Java has a lengthy item (it is either Item 1 or Item 2, I forget which) about using static factory methods. One of the first advantages it cites is that they behave like named constructors.
It is clear, even without reading the Javadoc, that LocalDate.now()
is going to return you a date which corresponds to "now". Whilst you could make a default constructor do the same, it would not be obvious.
Upvotes: 3
Reputation: 3430
Java8 DateTime
library give access to factory methods for creating objects of corresponding classes as opposed to constructors as it gives flexibility such as certain operations like parsing can be performed before the object is created. Also factory methods can have meaningful names as opposed to constructors. As mentioned in other answers you can use:
LocalDate localDate = LocalDate.now(); //creating LocalDate instance
Upvotes: 0
Reputation: 101
Use
LocalDate d = LocalDate.now();
to create a LocalDate for now. There are more static methods to instantiate a LocalDate. The designers of the API decided to create static methods to instantiate LocalDates because they can have more clear names on what is actually instantiated (like "now()" above to create a LocalDate for the current date).
Upvotes: 10
Reputation: 100133
The typical pattern here is a class with only private
or package default
constructors, combined with a factory method that is either a public static method of the class or a method of an accompanying factory class. You get LocalDate
objects from many static methods listed in the javadoc.
Upvotes: 14