Could someone please tell me why interfaces are preferred over abstract classes?
Java has both, and both are widely used, so it's not "use interfaces not abstract classes" but use the right one.
One big advantage to an abstract class is that it can contain code common to its subclasses. One big advantage to interfaces is that a single class can implement more than one interface, as Jos mentioned. As an example, class java.util.LinkedList implements all the interfaces Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E> and Queue<E>.
Can you have it both ways? Yes! There's a common pattern to the models in Swing:
-
public interface ListModel {...}
-
-
public abstract class AbstractListModel implements ListModel {...}
-
-
public class DefaultListModel extends AbstractListModel {...}
Here, interface ListModel describes what it takes to be the data inside a JList widget. Abstract class AbstractListModel provides the boilderplate code common to many list models -- you just have to implement two methods to complete it. Finally, DefaultListModel provides a complete solution that works right out of the box, in many cases. With this design you have plenty of options:
- Directly implement ListModel
- extend AbstractListModel
- directly use DefaultListModel
- extend DefaultListModel further
- etc...
So it's quite a flexible design, thanks to its combination of interface and abstract class.