Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help understanding abstract classes: java calendar method getInstance()

Tags:

java

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
like image 574
tmakino Avatar asked Feb 10 '11 18:02

tmakino


People also ask

What is calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.

Is calendar an abstract class in Java?

Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.

What is the use of calendar class in Java?

Java Calendar class is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable interface.


1 Answers

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();
    }
}
like image 192
Jon Skeet Avatar answered Nov 12 '22 23:11

Jon Skeet