user2309944
user2309944

Reputation:

how Abstract Calendar class's getInstance method returns a calendar Object

Hi I know that Abstract classes can't be instantiated. But in Java API Documentation here the calendar class is an Abstract class and there is a static getInstance() method which returns a Calendar object. If the Abstract calendar object can't be instantiated, so how this method returns a Calendar object?

Upvotes: 3

Views: 1012

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Calendar.getInstance() returns an instance of one of the concrete classes GregorianCalendar, BuddhistCalendar or JapaneseImperialCalendar depending on the locale. Each of theses classes is a Calendar because they all extend abstract Calendar. It's like here

abstract class A {
    public static A getInstance() {
          return new B();
    }
}

class B extends A {
}

Upvotes: 3

sanbhat
sanbhat

Reputation: 17622

getInstance() is a custom method and if you look at the jdk source, it is returning GregorianCalendar (or some other implementation of java.util.Calendar class).

I think you confused yourself thinking that getInstance() is Reflection method?

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122018

There is a singleton instance for each type of the calendar.

Calendar cal = Calendar.getInstance();

Upvotes: 0

Scott Woodward
Scott Woodward

Reputation: 325

It returns a class that extends Calendar, in this case java.util.GregorianCalendar, which can be checked with

Calendar cal = Calendar.getInstance();
System.out.println(cal.getClass());

A subclass can be stored within a variable of the parent class, even if the parent class cannot be instantiated directly.

Upvotes: 1

Related Questions