The Analogy: The Standard Method Statement With One Step Left Blank
A scaffolding contractor works from a standard method statement. Six numbered steps, printed on the same sheet for every job in the country: survey the ground, set the base plates, build to the first level, tie the tower, fit the guard rail, tag and hand over. The sheet exists so that no crew ever has to invent the order, and so that an inspector arriving on any site knows exactly what should already have happened.
Step 4 is deliberately blank. The line reads "tie the tower -- method to be specified", and there is nothing after the dash. That is not sloppiness at head office. Tying a tower to a brick wall, to a steel frame and to a glazed curtain wall are three genuinely different jobs with three different fixings, and head office cannot know which one this site has. The blank is the single decision that must be made per job, marked as such so that nobody can pretend it was already made.
The consequence is the part people find odd at first. You cannot work from the standard sheet. There is no such thing as "doing the standard method statement", because handing a crew a sheet with a hole in step 4 is handing them nothing. What actually goes in the site file is a job-specific statement that reproduces all six steps and fills in step 4 for this structure. The standard sheet is real, it is authoritative, and it is never itself used on a site.
Now the failure. Somebody at head office got tired of chasing site managers for step 4 and typed "tie as per standard practice" into the blank. Every job-specific statement is now complete on paper. Nobody is prompted, nobody is chased, the box is ticked -- and the curtain-wall job gets brick-wall ties, because the sheet said it was already decided. The blank was the only thing making anyone think. Replace it with a default that merely looks like an answer and you have not simplified the process; you have deleted the question.
Syntax or Core Structure
An abstract class is a class you cannot instantiate. An abstract method is a method with a signature and no body, which every concrete subclass must supply. Put the two together and you get a class that owns an algorithm but not all of its steps.
import java.util.ArrayList;
import java.util.List;
public abstract class MethodStatement {
protected final String job;
private int stepsDone;
protected MethodStatement(String job) {
this.job = job;
}
// Step 4 is blank. No sensible default exists, so do not invent one.
protected abstract String tieMethod();
// The fixed part: written once, shared by every job, and not negotiable.
public final String run() {
stepsDone = 0;
List<String> parts = new ArrayList<>();
parts.add(step("survey"));
parts.add(step("base"));
parts.add(step("build"));
parts.add(step(tieMethod())); // the hole, filled in by the subclass
parts.add(step("rail"));
parts.add(step("tag"));
return String.join(" ", parts);
}
private String step(String what) {
stepsDone++;
return stepsDone + ":" + what;
}
public int stepsDone() {
return stepsDone;
}
public static void main(String[] args) {
MethodStatement brick = new BrickTower("J-101");
MethodStatement steel = new SteelTower("J-102");
// MethodStatement bad = new MethodStatement("J-103"); // does not compile
System.out.println("brick " + brick.run());
System.out.println("steel " + steel.run());
System.out.println("steps " + brick.stepsDone());
System.out.println("job " + steel.job);
}
}
class BrickTower extends MethodStatement {
BrickTower(String job) {
super(job);
}
@Override
protected String tieMethod() {
return "bolt";
}
}
class SteelTower extends MethodStatement {
SteelTower(String job) {
super(job);
}
@Override
protected String tieMethod() {
return "clamp";
}
}
Output:
brick 1:survey 2:base 3:build 4:bolt 5:rail 6:tag
steel 1:survey 2:base 3:build 4:clamp 5:rail 6:tag
steps 6
job J-102
Four things happened there that are worth naming. run() was written once and produced two different sequences, because step 4 asked the object what to do rather than being told. The commented-out new MethodStatement(...) is a compile error, not a runtime one -- the language refuses the half-built thing outright. stepsDone reached 6 on an object whose class does not contain a single one of those six steps. And super(job) proves an abstract class has a constructor that really runs, even though nothing will ever call new on it directly.
Technical Depth: What abstract Actually Forbids, Why An Abstract Class Still Has A Constructor, And The Difference Between A Blank Step And A Bad Default
abstract is one prohibition and one permission, nothing more
Strip away the design talk and abstract does exactly two things. On a class it forbids new. On a method it permits a declaration with no body, and obliges the first concrete subclass to supply one. Everything else about an abstract class is completely ordinary.
| Can it... | Abstract class | Concrete class |
|---|---|---|
Be created with new | No -- compile error | Yes |
| Declare methods with no body | Yes | No |
| Have a constructor that really runs | Yes, via super(...) | Yes |
| Have mutable instance fields | Yes | Yes |
Have static members, including main | Yes | Yes |
Be marked final | No -- abstract final is a contradiction | Yes |
| Have zero abstract methods | Yes, and that is a legitimate design | Not applicable |
| Implement an interface without implementing its methods | Yes -- it inherits them as abstract | No |
Two rows in that table surprise people. An abstract class with no abstract methods at all is perfectly legal and sometimes exactly right: it says "this type is real and complete, but it is a category, not a thing". And an abstract class that implements Comparable without writing compareTo compiles fine; the unimplemented method is simply inherited as abstract and becomes the subclass's problem.
Why an abstract class has a constructor even though new is forbidden
The constructor of an abstract class is not decoration and it is not dead code. Every subclass constructor must invoke it, explicitly with super(...) or implicitly when there is a no-argument version, and it runs as step 2 of the four-step initialisation sequence -- before the subclass's own field initialisers. That is where shared invariants belong: validate the reference, assign the final fields, reject nonsense once instead of in every subclass.
Marking that constructor protected rather than public is worth the two extra characters. public on a constructor nobody can call is misleading; protected says out loud "this exists to be chained to, not called". And if you mark it private instead, only nested classes can extend the class at all -- which is the old way of writing a closed hierarchy, before sealed existed.
Blank step, sensible default, or sealed: choosing how a step varies
Every step in a template algorithm is one of four things, and the keyword you pick tells every future maintainer which.
| Kind of step | Declared as | Subclass obligation | Choose it when |
|---|---|---|---|
| Required decision | protected abstract T x(); | Must implement, or stay abstract | There is no correct default and getting it wrong matters |
| Optional extension | protected T x() { ... } | May override | The default is genuinely right in most cases |
| Fixed step | protected final T x() { ... } | Cannot override | The step must not vary, but subclasses may call it |
| Whole algorithm | public final void run() { ... } | Cannot override | The order of the steps is the contract |
Notice that run() in the example above is final. That is not caution for its own sake. The whole value of a template method is that the sequence is guaranteed; leave it overridable and a subclass can quietly reorder the steps or skip the tie altogether, and the guarantee you were selling evaporates.
A blank step and a bad default are not the same thing
This is the analogy's failure mode in code, and it is the most valuable twenty lines in the lesson. Both classes below are abstract. Both compile. One of them makes the compiler chase you until you have thought about the rate; the other quietly answers zero.
abstract class Checked {
protected abstract int rate(); // blank step: the compiler chases you
int fee(int units) { return units * rate(); }
}
abstract class Sloppy {
protected int rate() { return 0; } // looks complete, silently wrong
int fee(int units) { return units * rate(); }
}
class CheckedJob extends Checked {
@Override
protected int rate() { return 12; }
}
class SloppyJob extends Sloppy {
// rate() was never overridden. Nothing warned anybody.
}
public class Defaults {
public static void main(String[] args) {
System.out.println("checked " + new CheckedJob().fee(5));
System.out.println("sloppy " + new SloppyJob().fee(5));
}
}
Output:
checked 60
sloppy 0
SloppyJob is not a compile error, not a warning, and not a runtime exception. It is a bill for nothing, produced by a class that looks finished. Had Sloppy.rate() been abstract, SloppyJob would have refused to compile until somebody typed a number. That is the entire argument for preferring a blank step: it converts an invisible wrong answer into a visible unfinished one.
The test for whether a default is legitimate is not "can I think of a value" -- you can always think of zero. It is "if a subclass author never reads this method's documentation, is the default still correct for them?" If the honest answer is no, make it abstract. If you truly cannot, the next best thing is a default that throws UnsupportedOperationException with a message naming the method, which at least fails loudly on the first call rather than silently forever.
Calling an abstract method from a constructor
The constructors lesson showed that a constructor calling an overridable method sees the subclass override before the subclass is initialised. With an abstract method it is worse, because there is no base implementation to fall back on -- the override is the only thing that can run, and it runs too early by construction.
import java.util.ArrayList;
import java.util.List;
abstract class Panel {
Panel() {
System.out.println("during " + describe()); // the subclass override runs here
}
protected abstract String describe();
}
class Sized extends Panel {
private final int width;
private final List<String> notes = new ArrayList<>();
Sized() {
this.width = 900;
this.notes.add("set");
}
@Override
protected String describe() {
return "width " + width + " notes " + (notes == null ? -1 : notes.size());
}
}
public class TooEarly {
public static void main(String[] args) {
Sized s = new Sized();
System.out.println("after " + s.describe());
}
}
Output:
during width 0 notes -1
after width 900 notes 1
Both lines came from the same method on the same object. During Panel(), the blank final field width still held its default 0 and the notes field initialiser had not run yet, so notes was null -- and the only reason the first line is not a NullPointerException is the defensive check that a real describe() would never contain. The rule is blunt: a constructor may not call an abstract method, directly or through anything it calls. If the object needs a subclass-supplied value in order to be valid, take it as a constructor parameter instead.
Where the line with interfaces falls
An abstract class is the right tool when subclasses share state and an algorithm: fields to initialise, a fixed order of steps, a constructor that validates. An interface is the right tool when they share only a capability, and especially when a class needs to declare several. The two are not rivals so much as different halves of the same idea, and a common shape is an interface that names the capability plus an abstract class that implements the boring parts of it. The next lesson takes interfaces apart properly; for now, the question to ask is "do I need to hold data and control an order?" If yes, an abstract class. If no, almost certainly an interface.
Real World Example: A Council Inspection Pipeline Where The Order Is Law And One Step Is Different For Every Trade
A local authority certifies work on its housing stock. The sequence is set by policy and identical for every trade: pull the reference, collect the defects, weight each one, total the score, decide pass or fail, log it. What counts as a defect and how badly it counts are entirely trade-specific. That is an abstract class with two holes -- and one of the two has been given a default, on purpose, so you can watch what it does.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public abstract class Inspection {
protected static int issued = 0; // shared mutable static: the flaw
private static final int FAIL_AT = 5;
protected final String ref;
private final List<String> log = new ArrayList<>();
protected Inspection(String ref) {
this.ref = ref;
}
// Blank step: no default could possibly be right.
protected abstract List<String> defects();
// Blank step: every trade must name itself.
protected abstract String trade();
// Optional hook with a default that is deliberately far too generous.
protected int severityOf(String defect) {
return 1;
}
// The fixed algorithm. final, because the order is the policy.
public final String certify() {
log.clear();
List<String> found = defects();
int score = 0;
for (String d : found) {
int s = severityOf(d);
score += s;
log.add(d + "=" + s);
}
boolean pass = score < FAIL_AT;
if (pass) {
issued++;
}
return String.format(Locale.ROOT, "%-10s %-6s defects %d score %2d %s",
ref, trade(), found.size(), score, pass ? "PASS" : "FAIL");
}
public List<String> log() {
return List.copyOf(log);
}
public static int issued() {
return issued;
}
private static boolean froze(Inspection ins) {
try {
ins.log().add("tampered");
return false;
} catch (UnsupportedOperationException ex) {
return true;
}
}
public static void main(String[] args) {
Inspection elec = new ElectricalInspection("R-4471");
Inspection gas = new GasInspection("R-4472");
System.out.println(elec.certify());
System.out.println(gas.certify());
System.out.println("elec 1st " + elec.log().get(0));
System.out.println("elec 3rd " + elec.log().get(2));
System.out.println("gas 1st " + gas.log().get(0));
System.out.println("frozen " + froze(elec));
System.out.println("issued " + issued());
Inspection again = new GasInspection("R-4473");
again.certify();
System.out.println("issued 2 " + issued());
System.out.println("fail at " + FAIL_AT);
}
}
class ElectricalInspection extends Inspection {
ElectricalInspection(String ref) {
super(ref);
}
@Override
protected String trade() {
return "elec";
}
@Override
protected List<String> defects() {
return List.of("no RCD on socket circuit",
"loose earth at board",
"missing circuit chart");
}
// This trade did the work: real weights instead of the generous default.
@Override
protected int severityOf(String defect) {
if (defect.startsWith("no RCD")) {
return 4;
}
if (defect.startsWith("loose earth")) {
return 3;
}
return 1;
}
}
class GasInspection extends Inspection {
GasInspection(String ref) {
super(ref);
}
@Override
protected String trade() {
return "gas";
}
@Override
protected List<String> defects() {
return List.of("flue gap at ceiling",
"no isolation valve",
"corroded bracket",
"label missing");
}
// No severityOf override. Nothing complained.
}
Output:
R-4471 elec defects 3 score 8 FAIL
R-4472 gas defects 4 score 4 PASS
elec 1st no RCD on socket circuit=4
elec 3rd missing circuit chart=1
gas 1st flue gap at ceiling=1
frozen true
issued 1
issued 2 2
fail at 5
Read the two certificate lines together and the whole lesson is in them. The electrical inspection found three defects and failed. The gas inspection found four -- including a flue gap at the ceiling and a missing isolation valve -- and passed. Nothing is broken. certify() ran the identical six steps in the identical order for both, totalled the scores honestly and compared against the same threshold. The difference is that the electrician's subclass overrode severityOf and the gas subclass did not, so every gas defect scored 1 and four ones came to less than five.
That is the head-office pen in the blank box. severityOf was written with a default of 1 so that subclass authors would not be "burdened" with weighting every defect, and the result is a certificate that says PASS over a gas flue defect. Had severityOf been declared protected abstract int severityOf(String defect), GasInspection would not have compiled until somebody sat down and thought about gas. The compiler was willing to prevent this and was told not to bother.
The parts that work, work for reasons worth copying. certify() is final, so no trade can reorder the steps or skip the scoring. defects() and trade() are abstract, so a new trade cannot be added without answering both questions. Each subclass returns List.of(...), so the pipeline cannot mutate a trade's own defect list. log() hands out List.copyOf(log), which is why frozen true appears -- the caller's add threw UnsupportedOperationException instead of editing the council's record. And ref is protected final, assigned once in the abstract constructor that every subclass is forced to chain to.
Now the limits, and there are several beyond the headline. issued is a protected static int: mutable, shared by every trade, writable by any subclass in any package, and incremented without synchronisation, so issued 2 counting gas certificates from two different objects is the intended behaviour and a concurrent third inspection corrupting the count is the unintended one. FAIL_AT is a single threshold of 5 across every trade, which is exactly the kind of one-size number that made the gas result possible. certify() calls log.clear(), so certifying the same object twice silently destroys the first report's evidence. trade() may return null or any string at all, and String.format will print it happily. score is an unbounded int with no cap, so a subclass returning Integer.MAX_VALUE from severityOf overflows the sum negative and turns a catastrophic inspection into a PASS. And log is a plain ArrayList on a class with a static counter, so the whole type is unsafe to share between threads despite looking like a value object.
Common Mistakes
- Giving an abstract method a "harmless" default instead of leaving it abstract.
return 0;,return null;andreturn List.of();all look like tidy defaults and all convert a compile error into a silently wrong answer. If a subclass author who never reads your documentation would get the wrong result, the method must beabstract. - Calling an abstract method from the abstract class's constructor. The override runs before the subclass's fields are initialised, so it sees zeroes and nulls. There is not even a base implementation to fall back on. Take the value as a constructor parameter instead.
- Leaving the template method overridable. If
run()is notfinal, a subclass can reorder or skip the steps, and the guarantee that justified the abstract class in the first place is gone. - Marking the abstract class's constructor
public. Nobody can call it, sopublicis a lie.protectedsays accurately that it exists to be chained to. - Making every shared field
protected.protectedis wider than package-private -- it hands write access to every subclass in every package, forever. Preferprivateplus aprotectedaccessor, and reserveprotectedfields for cases you can justify out loud. - Using an abstract class where a plain interface would do. If the type has no fields, no constructor and no fixed order of operations, it is a capability, not a category. An abstract class costs the subclass its one
extendsslot; an interface costs it nothing. - Forgetting that a subclass may stay abstract. A subclass that implements only some of the inherited abstract methods is legal as long as it is itself declared
abstract. People add stub bodies to "fix" a compile error that was really telling them the hierarchy needed one more layer. - Writing
@Overridenowhere and assuming the method matched. Get one parameter type wrong and you have written a brand-new overload; the abstract method stays unimplemented and the error appears somewhere confusing.@Overrideturns that into a precise message on the right line. - Confusing "abstract" with "has abstract methods".
abstracton a class only forbidsnew. A class with no abstract methods at all can beabstract, and often should be when it represents a category no concrete instance should ever have.
Best Practices
- Make the algorithm
finaland the variationabstract. That pairing is the whole point of a template method: the caller gets a guaranteed sequence, the subclass gets exactly the decisions it is qualified to make. - Prefer a blank step to a default you cannot defend. Ask "would this default be right for an author who never read the docs?" If no, make it
abstract; if you cannot, throwUnsupportedOperationExceptionnaming the method rather than returning a plausible lie. - Put shared validation in the abstract constructor, and mark it
protected. Rejecting bad input once, before any subclass field exists, beats repeating the same three guards in four subclasses. - Keep abstract-class state
privateand expose it throughprotectedmethods. Subclasses get what they need without inheriting the right to corrupt it, and you keep the freedom to change the representation later. - Never call an overridable or abstract method from a constructor or an instance initialiser. If construction genuinely needs a subclass-supplied value, make it a constructor argument.
- Name the abstract class for the category, not the implementation.
Inspection,MethodStatementandPaymentall read as things a subclass is;AbstractInspectionHelperBasereads as an accident. - Give each abstract method a one-line contract in its Javadoc: what it must return, what it must never do, and whether
nullis allowed. A blank step is a question, and a question with no wording gets answered badly. - Reach for an interface first and promote to an abstract class only when you need state or order. Interfaces compose;
extendsdoes not, and a subclass only has one of them to spend.
Practice Exercises
- The Blank That Should Have Stayed Blank: Change
Inspection.severityOftoprotected abstract int severityOf(String defect)and fix the two subclasses so the file compiles again. GiveGasInspectionhonest weights -- flue gap 4, isolation valve 3, everything else 1 -- and report the new score, verdict andissuedcount. Then write two sentences explaining which line of the original code allowed a gas flue defect to be certified PASS. - The Half-Written Trade: Add an abstract
Plumbingsubclass ofInspectionthat implementstrade()andseverityOfbut deliberately leavesdefects()unimplemented, then two concrete subclasses of it,HotWaterandColdFeed, that supply different defect lists. Do not add any stub bodies. Explain whatPlumbingmust be declared as and why the compiler accepts it with one method still missing. - The Constructor That Asked Too Early: Take the
PanelandSizeddemo and rewrite it so the description is correct at construction time, without removing theSystem.out.printlnfromPanel's constructor. Then explain, in terms of the four initialisation steps, why passing the width tosuper(...)fixes what an abstractdescribe()never could.