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);
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With