Card 03/ 08

ConceptDifficulty: Intermediate1 min

Abstract Classes: Shared State and a Fixed Sequence

Three reports with the same header, footer and output stream, which an interface has nowhere to keep.

An abstract class is a class that cannot be instantiated on its own and may leave some methods without a body for subclasses to fill in. Unlike an interface, it is a class, so it can have fields and a constructor: it can hold state.

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:

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.