If you are developing an API that will be widely used, you should use both: an interface for expressing a contract that must be implemented through the implementation of classes, and an abstract class that partially implements this interface and thus allows code reuse.
As an example, consider the Java List: methods in the Collections structure (for example, Collections.sort ()) are written in terms of the List interface, which is partially implemented by the AbstractList class, which, in turn, expands to specific LinkedList and ArrayList implementations. LinkedList and ArrayList reuse the code from AbstractList, but this does not stop anyone from writing their own completely separate implementation of List, and then sorting it with Collections.sort ().
However, in many cases this approach may be excessive. If the type hierarchy you are building is used only in a relatively small area, you can simply use abstract classes in general. If you later decide that you want an interface later, this is a pretty painless refactoring task to make a difference.
Abstract classes have several advantages:
- they allow you to specify abstract methods with package / security modifiers
- they facilitate code reuse
- using abstract methods and final methods of the superclass, they allow you to limit the way your class is subclassed, which can be useful in a variety of circumstances (see also template template)
- which refers to classes is generally easier to execute in the IDE (clicking on an "open declaration" on an abstract type of a class type is usually more useful than on an interface type parameter)
anthem29
source share