Help understand abstract classes: java calendar getInstance () method

I find it difficult to understand the concept of abstract classes. The definition that I am reading is that they have at least one method that is declared but no implementation, so the class cannot be created. The java calendar class is abstract and cannot be created using the New operator, however there is a method called getInstance () that returns a calendar object. How it works?

Calendar cal = new Calendar(); //doesn't work Calendar cal = Calendar.getInstance(); //works 
+7
source share
5 answers

Abstract classes should not have abstract methods. This is how it is usually done.

Now Calendar.getInstance() works, actually creating an instance of the subclass. You can call it because it is a static method. The return value refers to an instance of the corresponding subclass, but the return type is just Calendar , which is good due to the usual inheritance rules.

Here is an example of the same approach, but without all the complexities of Calendar - the same principles apply:

 abstract class AbstractParent { public static AbstractParent getInstance() { // Normally you'd have code to work out which // concrete class to actually use return new ConcreteChild(); } public abstract void sayHello(); } class ConcreteChild extends AbstractParent { @Override public void sayHello() { System.out.println("Hello from ConcreteChild"); } } public class Test { public static void main(String[] args) { AbstractParent parent = AbstractParent.getInstance(); parent.sayHello(); } } 
+16
source

Since Calendar is an abstract class, you cannot create such a new instance. If you look at the doc , find any method with static Calendar specified on it, and you will find getInstance() so you can do something like this: -

 Calendar cal = Calendar.getInstance(); 

Now, if you look at the same document again, look at Direct Known Subclasses at the top of the page, the classes listed (here) are an implementation of the Calendar ... so in this case you can use GregorianCalendar , like this too: -

 Calendar cal = new GregorianCalendar(); 

Both work ...

+2
source
+1
source

The abstract CAN class implements static methods.

getInstance () is a static method that returns the concrete implementation of the abstract class by default.

In this case, I believe that it really returns an instance of GregorianCalendar.

+1
source

The getInstance () method of the Calendar class does not return an object of the Calendar class, instead it returns a calendar with a "default time zone and locale" in my case GregorianCalendar, which is a subclass of Calendar. :)

+1
source

All Articles