Could someone please explain to me the differences between abstract classes, interfaces, and mixins? I\'ve used each before in
In general:
An interface is a contract specifying operations, but without any implementation. Some languages (Java, C#) have baked-in support for interfaces, and in others 'interface' describes a convention like a pure virtual class in C++.
An abstract class is a class which specifies at least one operation without an implementation. Abstract classes can also provide some parts of their implementation. Again, some languages have baked-in support for marking classes as abstract and it is implicit in others. For example, in C++ a class which defines a pure virtual method is abstract.
A mixin is a class which is designed to make implementation of certain functionality easier in subclasses, but which is not designed to be used by itself. For example, say that we have an interface for an object that handles requests
interface RequestHandler {
void handleRequest(Request request);
}
Perhaps it would be useful to buffer the requests by accumulating them until we have some predetermined number and then flushing the buffer. We can implement the buffering functionality with a mixin without specifying the flush behavior:
abstract class BufferedRequestHandlerMixin implements RequestHandler {
List buffer = new List();
void handleRequest(Request request) {
buffer.add(request);
if (buffer.size == BUFFER_FLUSH_SIZE) {
flushBuffer(buffer);
buffer.clear();
}
}
abstract void flushBuffer(List buffer);
}
This way, it's easy for us to write a request handler that writes requests to disk, calls a web service, etc. without rewriting the buffering functionality each time. These request handlers can simply extend BufferedRequestHandlerMixin
and implement flushBuffer
.
Another good example of a mixin is one of the many support classes in Spring, viz. HibernateDaoSupport.