【问题标题】:Constructor for Instant class in Java?Java中即时类的构造函数?
【发布时间】:2018-06-01 10:45:04
【问题描述】:

我知道我可以通过这种方式创建一个 Instant 对象:

Instant instant = Instant.now();

我不明白为什么我不能像这样创建 Instant 对象:

Instant instant1 = new Instant();

我找不到关于 Instant 构造函数的任何信息,而且我知道 Instant 不是接口或抽象类。为什么我不能创建 Instant 对象?

提前致谢!

【问题讨论】:

标签: java time constructor instance


【解决方案1】:

因为构造函数是私有的。不要忘记有Java的开源实现,你可以简单地查看他们的implementations来解决这些问题:

/**
 * 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;
}

【讨论】:

  • @pkpnd java.time 实现是开源的;它不是由 Oracle 构建的,Oracle 的 Java 大部分与开源的 OpenJDK 相同。
【解决方案2】:

Instant 源代码声明了一个带有 2 个参数的 private 构造函数,这可以防止自动生成无参数构造函数。这是设计使然:Instant 源代码的作者想要阻止用户使用构造函数,因为他们想要强制用户使用 Instant.now()

【讨论】:

    【解决方案3】:

    使用私有构造函数是因为:

    • 有时我们想使用单例设计模式。为此,我们将类的构造函数声明为私有的,并创建 now() 方法来提供此功能。
    • 单例设计模式只为整个系统提供一个对象,这样我们就不会最终创建多个对象来优化我们的代码和垃圾回收。
      希望我能回答

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多