Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help understanding Calendar constructor vs method

 
Daniel Loranz
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep - I noted the "protected" next to the constructor. But why would a constructor be restricted this way?

Thanks.
 
Seamus Minogue
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Calendar is an abstract class, so you can't construct one by using new Calendar().
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic