Card 03/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
What an Abstract Class Adds That an Interface Cannot Hold
Three report types share the same header, the same footer and the same output stream, and differ only in the middle. Putting that shared machinery on an interface does not work, because the machinery needs somewhere to keep the stream.
An abstract class is a class that cannot be instantiated on its own and may leave some methods unimplemented. What makes it different from an interface is that it is a class, so it can hold state.
abstract class Report {
private final Writer out;
protected Report(Writer out) { this.out = out; }
final void render() throws IOException {
out.write("BEGIN\n");
body(out);
out.write("END\n");
}
protected abstract void body(Writer out) throws IOException;
}Line 2 is the part an interface cannot do: a private instance field, with a constructor to fill it. Line 11 is the hole each subclass fills. render() is final, so the order of header, body and footer is fixed for everyone.
| Compared on | Interface | Abstract class |
|---|---|---|
| Method signatures with no body | Yes | Yes |
| Methods with bodies | Yes, as default or static | Yes |
| Instance fields | No | Yes |
| Constructors | No | Yes |
| A class may have several | Yes | No — one parent only |
So the two are not competing ways of saying the same thing. One names a capability; the other supplies a partly-built class with somewhere to keep its own data.