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
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With