This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
If you ever want to know the exact class that is returned (and usually you don't need to know - that's the point of polymorphism - but it might be interesting) then just print out the value of theObj.getClass().getName().
I'm not sure, if really calling the getInstance() static method of the Calendar class, you really make an instance of GregorianCalendar. However abstract class can never be directly instantiated, there is something called "annonymous inner type", which allows you to create a no-name subclass of the abstract class and an instance of this:
As you can see, you must then implement all the abstract methods from the abstract superclass (Calendar in this case).
I think the getInstance() method of Calendar class might work like that.
Vijay Tidake wrote:If you look at the source of getInstance() will you see
And this is a perfect example of polymorphism in action. I don't know which version of the source code Vijay looked at but I looked at the 1.6_20 source code and it's createcalendar method looked like this
So, the code has been changed but anyone who uses the Calendar.getInstance method doesn't need to worry about it or make any changes to their source code to handle it.
The crucial point is that "Calendar.getInstance()" does NOT return an instance of the Calendar class - rather it returns whatever the getInstance mathod creates. That can't be an instance of Calendar, because that is abstract - it must be an instance of a subclass of Calendar that is not abstract. Mathew mentioned how you can determine what actual class that is.
Vijay Tidake wrote:
Although Calender class has a abstract method getInstance(), but when you say Calendar calc=Calendar.getInstance();
calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "
Calendar#getInstance() is not abstract, it is static. Two different things. The Calendar class is abstract.
Vijay Tidake wrote:
calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "
Not always. As quoted from the API Doc
Gets a calendar using the default time zone and locale.
If you actually look at the comment in the code snippet you posted, it can also return the Buddhist and JapaneseImperialCalendar which are not Gregorian