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 justCalendar, 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: