wood burning stoves 2.0*
The moose likes Cattle Drive and the fly likes help understanding Calendar constructor vs method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "help understanding Calendar constructor vs method" Watch "help understanding Calendar constructor vs method" New topic
Author

help understanding Calendar constructor vs method

Daniel Loranz
Ranch Hand

Joined: Jun 17, 2008
Posts: 41
I'm looking at the Calendar class and am a bit confused about the difference and use of the constructor Calendar() and the method getInstance() in the same class.

The constructor says "CONSTRUCTS a Calendar with the default time zone and locale."

The method says "GETS a calendar using the default time zone and locale." and returns a calendar object.

This seems very weird to me. Don't these do the same thing? I'm wondering if perhaps you are not allowed to invoke the constructor of this class. If so, why would that be the case?

The example given in the API shows ...

Calendar rightNow = Calendar.getInstance();

I would have expected something like ...

Calendar rightNow = new Calendar();
rightNow.someMethod();

Thanks for any help!
Seamus Minogue
Ranch Hand

Joined: Jun 24, 2008
Posts: 41
Well note that the Calendar constructor is marked as protected:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
Daniel Loranz
Ranch Hand

Joined: Jun 17, 2008
Posts: 41
Yep - I noted the "protected" next to the constructor. But why would a constructor be restricted this way?

Thanks.
Seamus Minogue
Ranch Hand

Joined: Jun 24, 2008
Posts: 41
Best guess would be the same reason you would make the constructor of a singleton private or protected. To force users to use the getInstance method.

You could probably find the code for Calendar on the web and take a look to see exactly what is going on inside the code

http://www.docjar.com/html/api/java/util/Calendar.java.html
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9046
    
  10
I think Calendar is an abstract class, so you can't construct one by using new Calendar().


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
 
GeeCON Prague 2014
 
subject: help understanding Calendar constructor vs method