Re: Calendar question
Rhino wrote:
Can someone clarify for me the difference between:
GregorianCalendar now = new GregorianCalendar();
<http://java.sun.com/javase/6/docs/api/java/util/
GregorianCalendar.html#GregorianCalendar()>
"Constructs a default GregorianCalendar using the current time in the
default time zone with the default locale."
and
Calendar now = Calendar.getInstance();
<http://java.sun.com/javase/6/docs/api/java/util/
Calendar.html#getInstance()>
"Gets a calendar using the default time zone and locale. ... based on
the current time ..."
Note that it does not say it gets a 'GregorianCalendar' instance.
and
Calendar now = GregorianCalendar.getInstance();
'GregorianCalendar' does not have a 'getInstance()' method. You
should refer to static members by the type that declares them, not
through subtypes.
I'm really not clear on what each does and when I would prefer one over t=
he
other. (I assume each one is preferred in some situation or another.)
Use 'new GregorianCalendar()' when you specifically want to construct
a 'GregorianCalendar' and not some other 'Calendar' type. You might
want this if the default 'Calendar' for the platform is some other
type, or if you want to control aspects not provided by the 'Calendar'
type, e.g., leap years.
For all other purposes, especially if you particularly want the
'Calendar' native to the host platform, use 'Calendar.getInstance()'.
In practice, this is nearly all the time.
This information is a combination of what's in the Javadocs, which of
course you have read thoroughly, and normal Java best practices, which
of course you are always studying.
<http://java.sun.com/docs/books/effective/>
"Item 1: Consider static factory methods instead of constructors"
which, of course, you have read and continue to reread periodically.
--
Lew