Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Calendar class not have a public constructor?

Tags:

java

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);
}
like image 634
bijiDango Avatar asked Sep 13 '25 01:09

bijiDango


2 Answers

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.

like image 200
Rahul Tripathi Avatar answered Sep 15 '25 14:09

Rahul Tripathi


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 constructor always returns a non-null instance of the specific class on which the constructor is invoked, or it throws an exception and you don't get a reference to the part-constructed instance;
  • A static factory method can return a subclass or null (or it throws an exception).

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.

like image 20
Andy Turner Avatar answered Sep 15 '25 14:09

Andy Turner