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
The point is to put what all subclasses share in one place, and to force each subclass to supply the parts that differ. A ShapeCircleRectangle
| Rule | Detail |
|---|---|
| Cannot be instantiated | new Shape(...)new Shape("x") { ... } |
| May have abstract methods | Only abstract classes (and interfaces) can declare methods without a body |
| Need not have any | An abstract class with no abstract methods is legal; it just cannot be instantiated |
| Has constructors | They run when a subclass is created, through super(...)protected |
| Can hold state | Instance fields of any access level, final or not |
| Subclasses must implement all abstract methods | Or be declared abstract themselves |
Cannot be final | A final class cannot be extended, which would make an abstract class useless |
Abstract methods cannot be privatestaticfinal | Each of those prevents a subclass from overriding the method |
A first example: shared code and abstract methods
The program defines an abstract Shapedescribearea
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:
circle area 7.07
rectangle area 7.00
Shape is abstract: true
is written once indescribe() but callsShape , which each subclass implements. Whenarea() runs on adescribe , the call toCircle goes toarea() : this is dynamic dispatch, covered inCircle.areainheritance and polymorphism .- The constructor is
, and theprotected field isname . Subclasses must pass a name throughprivate final , so a shape without a name cannot exist.super("circle") - The subclasses are
: the hierarchy is abstract at the top and closed at the bottom, which keeps it easy to reason about. Since Java 17, afinalsealed class can also limit which subclasses exist. - The list is declared as
, so code that uses it depends only on the abstract type.List<Shape>
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.
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:
name
Ada
Linus
2 rows
## Names
- Ada
- Linus
(2 names)
isrender , so no subclass can change the overall structure: header, then each row, then a footer.final andheader are abstract, so every report must provide them.formatRow is a hook: a method with a sensible default that subclasses may override.footer kept the default "2 rows" andCsvReport replaced it.MarkdownReport- The JDK uses this pattern widely:
is built on the abstractInputStream.read(byte[]) , andread() dispatches toHttpServlet.service anddoGet .doPost
Skeletal implementations: AbstractList
The collections framework ships abstract classes such as AbstractListAbstractMapAbstractSetListgetsize
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:
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 and the iterator used by the for-each loop all came fromequals , implemented with calls toAbstractList andget . Thesize interface has over 30 methods; this class wrote 2.List compared element by element with an ordinaryequals , becauseList.of implements the contract ofAbstractList , not identity.List.equals threwadd :UnsupportedOperationException 's version refuses, which is the right behavior for a read-only list. A modifiable list would also overrideAbstractList ,set andadd(int, E) .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.
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:
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
calledBase() ,describe() andcreated were stillname .null was already set, but only becauselabel is a compile-time constant: the compiler copies its value into every place that reads it."child label" is alsocreated , but its value is computed at run time, so it wasfinal . Beingnull does not protect a field here.final- Do not call overridable methods from a constructor. Since JDK 21,
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".javac -Xlint:this-escape
Abstract class or interface?
Since Java 8, interfaces can have defaultstaticprivateAccountPriced
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:
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
constructor rejected a negative opening balance, so no subclass can create an invalid account. The balance is aAccount field that subclasses use inprotected : 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.monthlyFeeCents needs no state: its defaultPriced method builds on the one abstract method. A record (label ) and an enum (Book ) implement it. Records and enums cannot extend any class, because they already extendTicket andRecord .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 | Interface | |
|---|---|---|
| Instance fields | Yes, any kind | No; only public static final |
| Constructors | Yes | No |
| Method bodies | Yes | defaultstaticprivate |
| Member access | Any, including protected | Public, except private helper methods |
| How many per class | One (single inheritance) | Any number |
| Usable by records and enums | No | Yes |
| Best for | A family of closely related classes sharing state and code | A 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
, make template methodsprotected , and never call overridable methods from a constructor.final