3

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!

  • 4
    Because the designers decided not to expose any constructor, and to promote factory methods instead. `Instant.now()` is much clearer than `new Instant()`. `Instant.ofEpochMilli(34567L)` is much clearer than `new Instant(34567L)`. – JB Nizet Jun 01 '18 at 10:47
  • 1
    read this [Java Pattern class doesn't have a public constructor, why?](https://stackoverflow.com/questions/13758740/java-pattern-class-doesnt-have-a-public-constructor-why) – Youcef LAIDANI Jun 01 '18 at 10:54

3 Answers3

3

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;
}
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
  • @pkpnd The `java.time` implementation is open source; it wasn't built by Oracle, and most of Oracle's Java is identical to OpenJDK, which is open source. – Mark Rotteveel Jun 01 '18 at 10:52
2

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.

k_ssb
  • 6,024
  • 23
  • 47
0

Private constructor is used because:

  • Sometimes we want to use the Singleton Design pattern. To achieve this, we declare our class's constructor as private and we create the now() method to provide this functionality.
  • Singleton Design pattern provides only one object for the entire system so that we don't end up creating multiple objects which optimize our code and garbage collection.
    Hope I answered
Md. Shahariar Hossen
  • 1,367
  • 10
  • 11