search

Home  >  Q&A  >  body text

java中的Calendar的getInstance()为什么可以返回Calendar对象

Calendar 类是一个抽象类,抽象类是不能实例化对象的。可是我在看API的时候看到这样的描述:

“Calendar 提供了一个类方法 getInstance,以获得此类型的一个通用的对象。Calendar 的 getInstance 方法返回一个 Calendar 对象,其日历字段已由当前日期和时间初始化: Calendar rightNow = Calendar.getInstance();”
我对这个很不解,为什么这个抽象类Calendar 可以通过getInstance()返回Calendar 对象。希望各位大神给出指点。十分感谢!!!

Calendar rightNow = Calendar.getInstance()
PHPzPHPz2767 days ago560

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:09:51

    First of all, abstract classes can have concrete implementation methods.
    Secondly, take a look at the source code:

    if ("th".equals(aLocale.getLanguage())
            && ("TH".equals(aLocale.getCountry()))) {
            return new sun.util.BuddhistCalendar(zone, aLocale);
        } else if ("JP".equals(aLocale.getVariant())
               && "JP".equals(aLocale.getCountry())
               && "ja".equals(aLocale.getLanguage())) {
            return new JapaneseImperialCalendar(zone, aLocale);
        }        
    
        // else create the default calendar
            return new GregorianCalendar(zone, aLocale);

    What this method ultimately returns is the specific implementation class, that is, the subclass, not the class that you understand as the instantiation of Calendar itself.

    reply
    0
  • Cancelreply