Abstract Classes in Java

An abstract class is a class that is not finished: it can hold fields, constructors and working methods, but leaves some methods for subclasses to implement, and it cannot be instantiated on its own. This page explains when that is the right tool, shows the patterns it is built for, the constructor trap that produces null fields, how the JDK's own AbstractList uses it, and how it compares with interfaces since Java 8.

Contents

What abstract means

A class marked abstract describes a family of objects without being a complete type itself. It can contain everything an ordinary class can, fields, constructors and implemented methods, plus abstract methods: methods with a signature but no body, which every concrete subclass must implement. Because those methods have no body, you cannot create an instance of the abstract class directly; you create instances of its subclasses.

The point is to put what all subclasses share in one place, and to force each subclass to supply the parts that differ. A Shape knows its name and how to describe itself, but only a Circle or Rectangle knows how to compute its area.

Rules for abstract classes
RuleDetail
Cannot be instantiatednew Shape(...) is a compile error; an anonymous subclass (new Shape("x") { ... }) is allowed
May have abstract methodsOnly abstract classes (and interfaces) can declare methods without a body
Need not have anyAn abstract class with no abstract methods is legal; it just cannot be instantiated
Has constructorsThey run when a subclass is created, through super(...); usually protected
Can hold stateInstance fields of any access level, final or not
Subclasses must implement all abstract methodsOr be declared abstract themselves
Cannot be finalA final class cannot be extended, which would make an abstract class useless
Abstract methods cannot be private, static or finalEach of those prevents a subclass from overriding the method

A first example: shared code and abstract methods

The program defines an abstract Shape with a name, a shared describe method and an abstract area, and two concrete subclasses. A circle of radius 1.5 and a 2 by 3.5 rectangle were picked because their areas are close (7.07 and 7.00), so the formatted output lines up and is easy to check.

Java
import java.lang.reflect.Modifier;
import java.util.List;

public class Shapes {

    // Abstract: cannot be instantiated, may have abstract methods and state
    abstract static class Shape {
        private final String name;

        protected Shape(String name) {       // subclasses must call this
            this.name = name;
        }

        abstract double area();              // every concrete shape must implement it

        String describe() {                  // shared, concrete behavior
            return String.format("%-9s area %7.2f", name, area());
        }
    }

    static final class Circle extends Shape {
        private final double r;

        Circle(double r) {
            super("circle");
            this.r = r;
        }

        @Override
        double area() {
            return Math.PI * r * r;
        }
    }

    static final class Rectangle extends Shape {
        private final double w;
        private final double h;

        Rectangle(double w, double h) {
            super("rectangle");
            this.w = w;
            this.h = h;
        }

        @Override
        double area() {
            return w * h;
        }
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1.5), new Rectangle(2, 3.5));
        for (Shape s : shapes) {
            System.out.println(s.describe());
        }
        // new Shape("x") would not compile: Shape is abstract
        System.out.println("Shape is abstract: "
                + Modifier.isAbstract(Shape.class.getModifiers()));
    }
}

Output:

Output
circle    area    7.07
rectangle area    7.00
Shape is abstract: true
  • describe() is written once in Shape but calls area(), which each subclass implements. When describe runs on a Circle, the call to area() goes to Circle.area: this is dynamic dispatch, covered in inheritance and polymorphism.
  • The constructor is protected, and the name field is private final. Subclasses must pass a name through super("circle"), so a shape without a name cannot exist.
  • The subclasses are final: the hierarchy is abstract at the top and closed at the bottom, which keeps it easy to reason about. Since Java 17, a sealed class can also limit which subclasses exist.
  • The list is declared as List<Shape>, so code that uses it depends only on the abstract type.

The template method pattern

The most common reason to write an abstract class is the template method: the abstract class fixes the order of the steps of an algorithm in a final method, and subclasses fill in individual steps. The program renders the same two rows as a CSV file and as a Markdown list.

Java
import java.util.List;

public class TemplateMethod {

    // The template method fixes the order of steps; subclasses fill in the details
    abstract static class Report {

        final String render(List<String> rows) {          // final: the order cannot change
            StringBuilder sb = new StringBuilder();
            sb.append(header()).append('\n');
            for (String row : rows) {
                sb.append(formatRow(row)).append('\n');
            }
            sb.append(footer(rows.size()));
            return sb.toString();
        }

        protected abstract String header();

        protected abstract String formatRow(String row);

        protected String footer(int count) {              // a hook with a default
            return count + " rows";
        }
    }

    static class CsvReport extends Report {
        @Override
        protected String header() {
            return "name";
        }

        @Override
        protected String formatRow(String row) {
            return row;
        }
    }

    static class MarkdownReport extends Report {
        @Override
        protected String header() {
            return "## Names";
        }

        @Override
        protected String formatRow(String row) {
            return "- " + row;
        }

        @Override
        protected String footer(int count) {
            return "(" + count + " names)";
        }
    }

    public static void main(String[] args) {
        List<String> rows = List.of("Ada", "Linus");
        System.out.println(new CsvReport().render(rows));
        System.out.println(new MarkdownReport().render(rows));
    }
}

Output:

Output
name
Ada
Linus
2 rows
## Names
- Ada
- Linus
(2 names)
  • render is final, so no subclass can change the overall structure: header, then each row, then a footer.
  • header and formatRow are abstract, so every report must provide them. footer is a hook: a method with a sensible default that subclasses may override. CsvReport kept the default "2 rows" and MarkdownReport replaced it.
  • The JDK uses this pattern widely: InputStream.read(byte[]) is built on the abstract read(), and HttpServlet.service dispatches to doGet and doPost.

Skeletal implementations: AbstractList

The collections framework ships abstract classes such as AbstractList, AbstractMap and AbstractSet. Each implements most of a large interface on top of a few abstract methods. The program creates a complete List of square numbers by writing only get and size; the squares are computed when asked for, so the list needs no storage.

Java
import java.util.AbstractList;
import java.util.List;

public class SkeletalList {

    // A read-only list of the squares 0, 1, 4, 9, ... computed on demand.
    // AbstractList asks for only two methods and builds the rest of List on top of them.
    static final class Squares extends AbstractList<Integer> {
        private final int size;

        Squares(int size) {
            this.size = size;
        }

        @Override
        public Integer get(int index) {
            if (index < 0 || index >= size) {
                throw new IndexOutOfBoundsException(index);
            }
            return index * index;
        }

        @Override
        public int size() {
            return size;
        }
    }

    public static void main(String[] args) {
        List<Integer> squares = new Squares(10);
        System.out.println("toString:    " + squares);
        System.out.println("contains 49: " + squares.contains(49));
        System.out.println("indexOf 64:  " + squares.indexOf(64));
        System.out.println("subList:     " + squares.subList(2, 5));
        System.out.println("equals:      " + squares.equals(List.of(0, 1, 4, 9, 16, 25, 36, 49,
                64, 81)));
        int sum = 0;
        for (int n : squares) {                      // iterator() also comes from AbstractList
            sum += n;
        }
        System.out.println("sum:         " + sum);
        try {
            squares.add(100);                        // not overridden, so it refuses
        } catch (UnsupportedOperationException e) {
            System.out.println("add:         UnsupportedOperationException");
        }
    }
}

Output:

Output
toString:    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
contains 49: true
indexOf 64:  8
subList:     [4, 9, 16]
equals:      true
sum:         285
add:         UnsupportedOperationException
  • toString, contains, indexOf, subList, equals and the iterator used by the for-each loop all came from AbstractList, implemented with calls to get and size. The List interface has over 30 methods; this class wrote 2.
  • equals compared element by element with an ordinary List.of, because AbstractList implements the contract of List.equals, not identity.
  • add threw UnsupportedOperationException: AbstractList's version refuses, which is the right behavior for a read-only list. A modifiable list would also override set, add(int, E) and remove(int).
  • This is the main remaining job of abstract classes now that interfaces can have default methods: providing a partial implementation together with the state or protected helpers it needs.

The constructor trap: calling abstract methods too early

A constructor of the abstract class runs before the subclass's fields are initialized. If that constructor calls an abstract method, the subclass's implementation runs on a half-built object. The program shows exactly which fields are already set at that moment.

Java
public class ConstructorTrap {

    abstract static class Base {
        Base() {
            System.out.println("Base constructor calls describe(): " + describe());
        }

        abstract String describe();
    }

    static class Child extends Base {
        private final String label = "child label";          // a compile-time constant
        private final String created = String.valueOf(2026); // computed at run time
        private String name;

        Child(String name) {
            super();                 // runs Base() before Child's fields are set
            this.name = name;
        }

        @Override
        String describe() {
            return "label=" + label + ", created=" + created + ", name=" + name;
        }
    }

    public static void main(String[] args) {
        Child c = new Child("alice");
        System.out.println("after construction:                " + c.describe());
    }
}

Output:

Output
Base constructor calls describe(): label=child label, created=null, name=null
after construction:                label=child label, created=2026, name=alice
  • Object creation runs the superclass constructor first, then the subclass's field initializers, then the rest of the subclass constructor. When Base() called describe(), created and name were still null.
  • label was already set, but only because "child label" is a compile-time constant: the compiler copies its value into every place that reads it. created is also final, but its value is computed at run time, so it was null. Being final does not protect a field here.
  • Do not call overridable methods from a constructor. Since JDK 21, javac -Xlint:this-escape warns about this pattern in public classes whose subclasses may be in other packages, with the message "possible 'this' escape before subclass is fully initialized".

Abstract class or interface?

Since Java 8, interfaces can have default and static methods, and since Java 9 private methods, so they now cover many uses that once needed an abstract class. The difference that remains is state and construction. The program shows an abstract Account that validates and holds a balance, and an interface Priced implemented by a record and an enum, which could never extend an abstract class.

Java
import java.util.List;

public class AbstractVsInterface {

    // An abstract class can hold state, check it in a constructor, and keep members protected
    abstract static class Account {
        private final String id;
        protected long balanceCents;

        protected Account(String id, long openingCents) {
            if (openingCents < 0) {
                throw new IllegalArgumentException("negative opening balance");
            }
            this.id = id;
            this.balanceCents = openingCents;
        }

        abstract long monthlyFeeCents();

        final void endOfMonth() {
            balanceCents -= monthlyFeeCents();
        }

        @Override
        public String toString() {
            return id + ": " + balanceCents + " cents";
        }
    }

    static final class Checking extends Account {
        Checking(String id, long cents) {
            super(id, cents);
        }

        @Override
        long monthlyFeeCents() {
            return balanceCents < 100000 ? 500 : 0;   // free above 1,000.00
        }
    }

    // An interface describes a capability; records and enums can implement it too
    interface Priced {
        long priceCents();

        default String label() {                       // shared behavior without state
            return String.format("%d.%02d", priceCents() / 100, priceCents() % 100);
        }
    }

    record Book(String title, long priceCents) implements Priced { }

    enum Ticket implements Priced {
        ADULT(1250), CHILD(600);

        private final long cents;

        Ticket(long cents) {
            this.cents = cents;
        }

        @Override
        public long priceCents() {
            return cents;
        }
    }

    public static void main(String[] args) {
        Account a = new Checking("ACC-1", 80000);
        Account b = new Checking("ACC-2", 250000);
        a.endOfMonth();
        b.endOfMonth();
        System.out.println(a + ", " + b);
        try {
            new Checking("ACC-3", -1);
        } catch (IllegalArgumentException e) {
            System.out.println("constructor check: " + e.getMessage());
        }

        List<Priced> items = List.of(new Book("Java", 4999), Ticket.ADULT, Ticket.CHILD);
        for (Priced p : items) {
            System.out.println(p + " costs " + p.label());
        }
    }
}

Output:

Output
ACC-1: 79500 cents, ACC-2: 250000 cents
constructor check: negative opening balance
Book[title=Java, priceCents=4999] costs 49.99
ADULT costs 12.50
CHILD costs 6.00
  • The Account constructor rejected a negative opening balance, so no subclass can create an invalid account. The balance is a protected field that subclasses use in monthlyFeeCents: ACC-1, under 1,000.00, paid a 5.00 fee; ACC-2 did not. Neither is possible in an interface, which has no instance fields or constructors.
  • Priced needs no state: its default label method builds on the one abstract method. A record (Book) and an enum (Ticket) implement it. Records and enums cannot extend any class, because they already extend Record and Enum.
  • A class can implement any number of interfaces but extend only one class, so choosing an abstract class uses up the single inheritance slot.
Abstract class compared with interface
Abstract classInterface
Instance fieldsYes, any kindNo; only public static final constants
ConstructorsYesNo
Method bodiesYesdefault, static (Java 8) and private (Java 9) methods
Member accessAny, including protectedPublic, except private helper methods
How many per classOne (single inheritance)Any number
Usable by records and enumsNoYes
Best forA family of closely related classes sharing state and codeA capability that unrelated types can have

When to use an abstract class

  • Use one when several classes share state and behavior, and the shared part needs constructors, invariants or protected members: the template method and skeletal implementations are the classic cases.
  • Prefer an interface when you are describing what a type can do, especially if records, enums or classes from different hierarchies should all be able to do it. Interfaces with default methods give most of the code reuse without using up the superclass.
  • Prefer composition, passing in an object that does the varying part, when the "abstract method" is really a strategy that could be swapped at run time. A lambda or functional interface is often simpler than a subclass.
  • Keep constructors protected, make template methods final, and never call overridable methods from a constructor.