Lesson 12 of 23

In progress

Course progress

Java

Abstract classes

Share a partial implementation, leave the varying part abstract, and use the template method without hiding the flow.

An abstract class sits between an interface and a concrete class: it can hold state and provide some behaviour, while leaving specific steps to its subclasses.

What you will learn

  • Declare abstract methods and classes.
  • Share code without sharing everything.
  • Apply the template method pattern and know its limits.

The declaration

public abstract class Report {
private final String title;
protected Report(String title) {
this.title = title;
}
final void render() {
System.out.println("== " + title + " ==");
body();
System.out.println("-- end --");
}
protected abstract void body();
}

Report cannot be instantiated: new Report("x") is a compile error. It exists to be extended, and body is the part each subclass must supply.

public class SalesReport extends Report {
SalesReport() { super("Sales"); }
@Override
protected void body() {
System.out.println("42 orders, 1,250,000 paise");
}
}

render is final, so the overall structure cannot be changed. A subclass supplies the content and nothing else. That is the template method pattern: the parent defines the sequence, the child fills the gap.

Why keep the sequence in the parent

If every subclass wrote its own render, the heading style would drift and a later change would need editing in five places. Keeping it in the parent makes the format a single decision.

The cost is rigidity: a subclass that needs a different structure must either override the whole thing (impossible while render is final) or the design must offer a hook. Add hooks only where variation is real, because abstract methods are commitments for every subclass.

Abstract versus concrete methods

protected void footer() {
System.out.println("Generated by tutorials.in");
}

A concrete method in an abstract class is inherited as-is and can be overridden unless final. That is how you share code: the common part lives once, and subclasses override only where they differ.

The mix is the point. An interface gives a contract with no state; an abstract class gives a contract plus an implementation plus fields. When you need all three, it is the right tool.

Constructors and initialisation

An abstract class can have a constructor, and subclasses must call it:

abstract class Task {
private final String name;
Task(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("name required");
}
this.name = name;
}
String name() { return name; }
}

Validation in the parent constructor runs for every subclass, so the rule holds across the family. That is a real benefit over an interface, which cannot enforce anything at construction.

Hooks with sensible defaults

public abstract class Importer {
public final int run(String path) {
String raw = read(path);
String clean = preprocess(raw);
int rows = parse(clean);
afterImport(rows);
return rows;
}
protected abstract String read(String path);
protected abstract int parse(String raw);
protected String preprocess(String raw) { return raw; }
protected void afterImport(int rows) { }
}

preprocess and afterImport are optional steps with do-nothing defaults. A subclass overrides them only if it needs to. The required steps are abstract, so the compiler enforces them.

That shape is common in frameworks and worth recognising: a final orchestrator, abstract required steps, optional overridable hooks.

Design cautions

Inheritance is the tightest coupling in Java. A subclass depends on the parent’s method calls, their order and their contracts, so a change to the parent can break children that were never touched.

Two habits reduce the risk:

  • Keep the abstract surface small: few abstract methods, few protected fields.
  • Prefer composition when the relationship is "uses" rather than "is a".

An abstract class with ten abstract methods forces every subclass to implement all of them, including ones it does not care about. Interfaces that can be implemented selectively, or small abstract classes per concern, are easier to live with.

Sealed hierarchies

Recent Java lets a class declare which subclasses are allowed:

public sealed abstract class Shape permits Circle, Square { }
final class Circle extends Shape { }
final class Square extends Shape { }

A sealed hierarchy makes the set of subtypes closed, so a switch over it can be checked for completeness. It is the strongest form of "this family is fixed", and it pairs well with pattern matching.

Abstract class or interface

Choose an abstract class when you have state to share, a constructor to enforce, or a sequence to fix. Choose an interface when the contract is the whole story and implementations may be unrelated.

Choosing both is common and effective: a small interface for the contract, an abstract class implementing it for the shared parts, and concrete classes extending that.

Making the orchestrating method overridable and calling abstract methods from its constructor. Subclasses are not initialised at that point, so fields are still null; call abstract methods from a method invoked after construction instead.

Write an abstract Exporter with a final export(List<String> rows) that prints a header, each row, and a count, plus an abstract header(). Implement a CSV exporter and a pipe-separated exporter.

Show solution
import java.util.List; public abstract class Exporter { public final void export(List<String> rows) { System.out.println(header()); for (String row : rows) { System.out.println(row); } System.out.println("rows: " + rows.size()); } protected abstract String header(); } class CsvExporter extends Exporter { protected String header() { return "id,name"; } } class PipeExporter extends Exporter { protected String header() { return "id|name"; } }

Both subclasses change only the header, while the loop and the count are written once. If the format later needs a footer, it is added in Exporter and both subclasses inherit it.

Recap

  • An abstract class cannot be instantiated and can mix concrete and abstract methods.
  • A final orchestrator with abstract steps fixes the sequence and lets subclasses supply the variation.
  • Keep the abstract surface small, and prefer composition when the relationship is not "is a".

Next, packages: grouping classes and controlling what the rest of the program can see.

Can an abstract class have no abstract methods?
Yes, which makes it non-instantiable but otherwise complete. That is rare and usually a sign the class should be concrete.
Can an abstract method be private?
No. A private method cannot be overridden, so it cannot be abstract.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.