简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM