Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor for Instant class in Java?

I know that I can create an Instant object in this way:

Instant instant = Instant.now();

And I don't understand why I can't create an Instant object like this:

Instant instant1 = new Instant();

I can't find any informations about Instant constructors, and I know Instant is not an interface or abstract class. Why I can't create an Instant object?

Thanks in advance!


2 Answers

Because the constructor is private. Don't forget that there are open source implementations of Java, and you can simply look at their implementations for such questions:

/**
 * Constructs an instance of {@code Instant} using seconds from the epoch of
 * 1970-01-01T00:00:00Z and nanosecond fraction of second.
 *
 * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
 * @param nanos  the nanoseconds within the second, must be positive
 */
private Instant(long epochSecond, int nanos) {
    super();
    this.seconds = epochSecond;
    this.nanos = nanos;
}
like image 179
Max Vollmer Avatar answered Jun 21 '26 08:06

Max Vollmer


The Instant source code declares a private constructor taking 2 arguments, which prevents auto-generation of the no-arg constructor. This is by design: the authors of the Instant source code wanted to prevent users from using the constructor, because they wanted to force users to use Instant.now() instead.

like image 27
k_ssb Avatar answered Jun 21 '26 10:06

k_ssb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!