Card 03/ 08

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.

java
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.

What each of the two may contain
Compared onInterfaceAbstract class
Method signatures with no bodyYesYes
Methods with bodiesYes, as default or staticYes
Instance fieldsNoYes
ConstructorsNoYes
A class may have severalYesNo — 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.