I\'ve been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever rea
One method of choosing between an interface
and a base class
is the consideration of code ownership. If you control all the code then a base class is a viable option. If on the other hand many different companies might want to produce replaceable components, that is define a contract then an interface is your only choice.
Use an interface to define behavior. User (abstract) classes (and subclasses) to provide implementation. They are not mutually exclusive; they can all work together.
For example, lets say you are defining a data access object. You want your DAO to be able to load data. So put a load method on the interface. This means that anything that wants to call itself a DAO must implement load. Now lets say you need to load A and B. You can create a generic abstract class that is parameterized (generics) to provide the outline on how the load works. You then subclass that abstract class to provide the concrete implementations for A and B.
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
.
I found some articles, particularly some who describe why you should not use implementation inheritance (i.e. superclasses):
If you only want to inherit method signatures (name, arguments, return type) in the subclasses, use an interface, but if you also want to inherit implementation code, use a superclass.