Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate hasn't constructor... How can we create classes without constructor?

Tags:

java

java-8

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.

like image 517
brais1912 Avatar asked Aug 31 '18 19:08

brais1912


People also ask

Can I create a class without constructor?

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.

Can we create a class without constructor in Java?

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.

What happens if constructor is not there?

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.

Does every class have a constructor?

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.


2 Answers

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).

like image 190
Casper Groenen Avatar answered Nov 03 '22 00:11

Casper Groenen


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.

like image 21
bmargulies Avatar answered Nov 03 '22 02:11

bmargulies