Reputation: 1596
Will new Calendar()
have any difference from Calendar.getInstance()
?
The question is just as simple as it is........... Since the system refuse to post it, I just copy some nonsense here.
private static Calendar calendar = Calendar.getInstance();
public static int getCalendar(long time, int calendarConst) {
calendar.setTimeInMillis(time);
return calendar.get(calendarConst);
}
Upvotes: 4
Views: 766
Reputation: 7636
When you do new Calendar()
, it creates new calendar instance from the default Calendar instance. Sometimes creating an instance via constructor is not good as creating from Factory methods. That's why it uses Factory methods to create an instance.
And,
Calendar.getInstance()
is a native method, and note down native methods don't have body/implementation. They have implemented already from the system.
It writes here: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html.
And, as explained in above answers already, the calendar instance is created by calling Calendar class. Static Factory design pattern to create calendar instance.
Upvotes: -1
Reputation: 140484
There is a detailed account of the difference between constructors and static factory methods in Effective Java second edition, which is well worth a read.
The main difference here is in what the two return:
The latter case is exactly what Calendar.getInstance()
does: you clearly don't get back an instance of Calendar
itself, since it is abstract, but instead you might get a GregorianCalendar
, JapaneseImperialCalendar
etc.
This decouples Calendar
's implementation from the client code: you can make changes to Calendar
without the client needing to make changes.
Upvotes: 2
Reputation: 172528
I think the answer is simple Calendar is an Abstract class, so we cant create an instance of it. Now when you call Calendar.getInstance
then GregorianCalendar
instance is created.
Upvotes: 5