Why Use an Interface Together With an Abstract Class?
I often come across code where developers prefer to program to interfaces, particularly when the code is designed to be extended. Unfortunately, that approach can cause problems with backward compatibility. Take the following example.
public class Registry {
public List plugins;
}public interface Plugin {
public void doSomehing();
}public class PluginA implements Plugin {
public void doSomehing();
}If you do this, you're setting yourself up for trouble. Whenever you add a new method to the Plugin interface, you automatically break every class that implements it, including PluginA in our example. Often you'll also break code you don't even know exists. In your own code, the size of the problem depends on how large a codebase you have to search through.
That's why you should always provide an interface together with an abstract class that implements it.
public abstract AbstractPlugin implements Plugin {
public void doSomehing(){}
}That way, you can add to the interface and supply a default implementation. If the change to the interface is substantial, consider creating a new interface derived from the original one.
Using only an abstract class in place of the interface is too restrictive. Every extension would have to inherit from your class. The interface and abstract class together give you the best combination.
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio