The main reason for using abstract classes and interfaces are different.
An abstract class should be used when you have classes that have identical implementations for a bunch of methods, but vary in a few.
This may be a bad example, but the most obvious use of abstract classes in the Java framework is within the java.io classes. OutputStream
is just a stream of bytes. Where that stream goes to depends entirely on which subclass of OutputStream
you're using... FileOutputStream
, PipedOutputStream
, the output stream created from a java.net.Socket
's getOutputStream
method...
Note: java.io also uses the Decorator pattern to wrap streams in other streams/readers/writers.
An interface should be used when you just want to guarantee that a class implements a set of methods, but you don't care how.
The most obvious use of interfaces is within the Collections framework.
I don't care how a List
adds/removes elements, so long as I can call add(something)
and get(0)
to put and get elements. It may use an array (ArrayList
, CopyOnWriteArrayList
), linked list (LinkedList
), etc...
The other advantage in using interfaces is that a class may implement more than one. LinkedList
is an implementation of both List
and Deque
.