How is it possible for the abstract class Calendar to have a method that return its instance? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How is it possible for the abstract class Calendar to have a method that return its instance?

Hello guys! Yesterday I was studying a Java code and I saw the use of Calendar class for the first time. The material said that it was an abstract class and that there were other concrete class that inherited it (e.g. Gregorian calendar). But the material used the static method 'Calendar.getInstance()' that returns an instance for Calendar class and I cannot understand why this works since an abstract class cannot be instantiated directly. I tried to copy the behavior of the Calendar class creating an abstract class with the method getInstance returning its instance, but how I expected it generated an error. https://code.sololearn.com/cQK9JoJMj08B/?ref=app PS: Sorry for the text if it contains grammatical erros, I'm not good in english (I used Google Translator to helped me with it) - I'm brazilian 😄

22nd Mar 2021, 5:41 PM
Allan Jackson
Allan Jackson - avatar
1 Answer
+ 1
Ah, I guess I got it! So, the class creates an instance of a concrete type, like GregorianCalendar, inside the method and returns it as a supertype variable, just like as it was an interface, right? Would it be possible to get the concrete subtype that was returned? Or would it only return the supertype Calendar as response?
22nd Mar 2021, 6:08 PM
Allan Jackson
Allan Jackson - avatar