我知道我可以这样创建一个Instant对象:
Instant instant = Instant.now();我不明白为什么我不能像这样创建一个Instant对象:
Instant instant1 = new Instant();我找不到任何关于Instant构造函数的信息,我知道Instant不是一个接口或抽象类。为什么我不能创建Instant对象?
提前感谢!
发布于 2018-06-01 18:48:29
因为构造函数是私有。不要忘记,有一些开放源码的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;
}发布于 2018-06-01 18:48:08
Instant源代码声明了一个带有2个参数的private构造函数,这阻止了无参数构造函数的自动生成。这是经过设计的:Instant源代码的作者希望阻止用户使用构造函数,因为他们希望强制用户使用Instant.now()。
发布于 2021-09-13 17:10:36
使用私有构造函数是因为:
now()方法来提供此functionality.希望我回答了
https://stackoverflow.com/questions/50641710
复制相似问题