简体   繁体   中英

help understanding abstract classes: java calendar method getInstance()

I'm having trouble understanding the concept behind abstract classes. The definition I'm reading is that they have at least one method which is declared but lack implementation, thus the class can't be instantiated. The java calendar class is abstract and can't be instantiated using the New operator, however there's a method called getInstance() which returns a calendar object. How does this work?

Calendar cal = new Calendar(); //doesn't work
Calendar cal = Calendar.getInstance(); //works

Abstract classes don't have to have any abstract methods. That's just how it's usually done.

Now Calendar.getInstance() works by actually creating an instance of a subclass. You're allowed to call it because it's a static method. The return value refers to an instance of the relevant subclass, but the return type is just Calendar , which is fine due to the normal rules of inheritance.

Here's an example of the same sort of 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();
    }
}

Since Calendar is an abstract class, you cannot create a new instance like that. If you look at the doc , find any method with static Calendar listed 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 doc again, look at Direct Known Subclasses at the top of the page, the listed class(es) here are the implementation of Calendar... so, in this case, you can use GregorianCalendar , like this too:-

Calendar cal = new GregorianCalendar();

Both works...

An abstract class CAN implement static methods.

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

In this case, I believe it actually returns a GregorianCalendar instance.

The getInstance() method of the Calendar class doesn't return an object of the Calendar class, instead it returns a calendar with the "default timezone and locale" in my case a GregorianCalendar wich is a subclass of Calendar. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM