After encountering a few abstract classes in different open source projects, I found myself asking the question, why? After some searching, here are a few good answers to the question, prefaced by a quick summary by myself:
- What is an abstract class?
An abstract class is one that cannot be instantiated itself, but can be extended by subclasses.
- Why not just use a base class?
An abstract class is useful in cases where you do not want your base class to be called for direct use, yet still want to establish common functionality with it.
- Why is it recommended not to implement in the abstract class?
This “best practice” seems silly at first, considering that you defeat the purpose of inheritance by avoiding implementation. My recommendation is to declare all abstract methods for complete class reference, while returning to implement anything that make sense to be common code.
- What if I want to follow convention?
Then what you are really creating is an “interface,” not an abstract class. An interface strictly outlines the members and methods only, with no implementation allowed.
- So whats the value of an interface?
An interface is useful to control code in a program that you know will be worked on by many others. What if you have a group of subclasses whose functionality depend on certain methods being available? Requiring that the subclass implement an interface forces all methods in the interface to be implemented by the subclass at instantiation. This prevents subclasses created by others from breaking the overall application by missing key methods. This has nothing to do with ease-of-coding, which may make it appear as an necessary process to the lone developer. Rather, the advantage of an interface speaks to the much broader world project management.