![](/img/trans.png)
[英]Why does only the class with the static method have the error: “Add a private constructor to hide the implicit public one.”?
[英]Why does the Calendar class not have a public constructor?
将new Calendar()
有任何差别Calendar.getInstance()
这个问题就这么简单...........由于系统拒绝发布它,因此我在这里复制了一些废话。
private static Calendar calendar = Calendar.getInstance();
public static int getCalendar(long time, int calendarConst) {
calendar.setTimeInMillis(time);
return calendar.get(calendarConst);
}
我认为答案很简单Calendar是一个Abstract类,因此我们无法创建它的实例。 现在,当您调用Calendar.getInstance
时,将创建GregorianCalendar
实例。
在Effective Java第二版中详细说明了构造函数和静态工厂方法之间的区别,非常值得一读。
这里的主要区别在于两者的返回值:
后一种情况正是Calendar.getInstance()
所做的:由于它本身是抽象的,因此您显然不会返回Calendar
本身的实例,但是相反,您可能会得到GregorianCalendar
, JapaneseImperialCalendar
等。
这使Calendar
的实现与客户端代码脱钩:您可以对Calendar
进行更改,而无需客户端进行更改。
当您执行new Calendar()
,它将根据默认的Calendar实例创建新的日历实例。 有时通过构造函数创建实例不如从Factory方法创建实例。 这就是为什么它使用Factory方法创建实例的原因。
和,
Calendar.getInstance()
是本机方法, 请注意本机方法没有正文/实现。 他们已经从系统中实现了。
它写在这里: https : //www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html 。
并且,正如上面答案中已经解释的那样,日历实例是通过调用Calendar类创建的。 用于创建日历实例的静态Factory设计模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.