bijiDango
bijiDango

Reputation: 1596

Why does the Calendar class not have a public constructor?

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);
}

Upvotes: 4

Views: 766

Answers (3)

Uddhav P. Gautam
Uddhav P. Gautam

Reputation: 7636

When you do new Calendar(), it creates new calendar instance from the default Calendar instance. Sometimes creating an instance via constructor is not good as creating from Factory methods. That's why it uses Factory methods to create an instance.

And,

Calendar.getInstance() is a native method, and note down native methods don't have body/implementation. They have implemented already from the system.

It writes here: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html.

And, as explained in above answers already, the calendar instance is created by calling Calendar class. Static Factory design pattern to create calendar instance.

Upvotes: -1

Andy Turner
Andy Turner

Reputation: 140484

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.

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172528

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.

Upvotes: 5

Related Questions