![](/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.