本帖最后由 庄星睿 于 2012-7-2 22:24 编辑
Calendar类是个抽象类,抽象类是不能实例化对象的,只能由其子类实例化,但Calendar.getInstance()方法,返回了一个Calendar对象,还可以调用其方法
Calendar c=Calenar.getInstance();
c.get(Calendar.YEAR);
c.add(Calendar.YEAR,-1);
我看源码了,用的不是单例模式,单例是隐藏了自己的构造方法,本身创建了对象,通过公共的public static Object getInstance()获取对象,但抽象类本身就不能创建对象的,那个Calendar.getInstance().他获取的的对象是谁创建的
搞明白了,学习的时候漏掉了 GregorianCalendar ,他是Calendar的子类,通过子类对象实例化后再调用方法
源码:
public static Calendar getInstance()
{
Calendar cal = createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
cal.sharedZone = true;
return cal;
}
private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
Calendar cal = null;
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype == null) {
// Calendar type is not specified.
// If the specified locale is a Thai locale,
// returns a BuddhistCalendar instance.
if ("th".equals(aLocale.getLanguage())
&& ("TH".equals(aLocale.getCountry()))) {
cal = new BuddhistCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
} else if (caltype.equals("japanese")) {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else if (caltype.equals("buddhist")) {
cal = new BuddhistCalendar(zone, aLocale);
} else {
// Unsupported calendar type.
// Use Gregorian calendar as a fallback.
cal = new GregorianCalendar(zone, aLocale);
}
return cal;
}
|
|