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.
Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
The constructor lets you create instances of the class with the new keyword. Like this: Test test = new Test(); // This calls the default constructor. If there weren't constructors in Java, you wouldn't be able to create objects.
Every class has a constructor whether it's a normal class or a abstract class. Constructors are not methods and they don't have any return type. Constructor name should match with class name . Constructor can use any access specifier, they can be declared as private also.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With