Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 201 ยท Object-Oriented Programming

Abstraction and Abstract Classes

Learn abstraction in Java - abstract classes and methods, the rules the compiler enforces, constructors in abstract classes and the template method pattern.

When you press the brake pedal in a car, you don't think about hydraulic pressure, brake pads or anti-lock sensors. The pedal is a simple promise ("this slows the car down") and the messy details are hidden behind it. That idea is called abstraction: show what something does and hide how it does it.

In Java you've already used abstraction many times. List.add works the same whether the list is an ArrayList or a LinkedList; IO.println hides everything about consoles and character encodings. This lesson shows how to build your own abstractions with abstract classes: classes that describe a family of related types, provide the shared parts, and leave specific steps for subclasses to fill in. It builds on Inheritance and Polymorphism and Method Overriding, so review those if extends and @Override are still new.

Abstraction in one example

Imagine a drawing app with circles, rectangles and triangles. Every shape has an area and can describe itself, but each computes its area differently. The code that uses shapes (summing areas, sorting by size, printing a report) shouldn't care which kind it has. It should talk to a general idea of "a shape".

You could write a regular Shape class with an area() method that returns 0, and let subclasses override it. That works, but it's a lie: there is no such thing as a plain shape with area zero, and nothing stops a programmer from writing new Shape() or forgetting to override area() in a new subclass. An abstract class fixes both problems.

Declaring an abstract class

Put the abstract modifier on the class and on each method that has no sensible general implementation. An abstract method ends with a semicolon instead of a body:

Java
abstract class Shape {
    abstract double area();          // no body: every subclass must supply one

    String describe() {              // a normal, concrete method
        return "%s with area %.2f".formatted(getClass().getSimpleName(), area());
    }
}

Two rules follow immediately:

  • You can't create an object of an abstract class. new Shape() is a compile error, because the object would have a method with no code.
  • A concrete subclass must implement every abstract method. If it doesn't, the compiler refuses it, unless the subclass is declared abstract too.
Java An abstract Shape with two concrete subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at what happened. describe() is written once, in Shape, yet it calls area(), which has no code in Shape. At run time, dynamic dispatch sends each call to the subclass's version, so a circle reports a circle's area. The loop only knows the type Shape, which is the whole point: you can add Triangle tomorrow without touching the loop.

Abstract types work as variable types, parameter types, array element types and generic type arguments (List<Shape>). The only thing you can't do is instantiate them directly.

What the compiler enforces

Abstract classes are useful because the compiler checks the promises for you. Here is what goes wrong when you break the rules:

Java
Shape s = new Shape();
// error: Shape is abstract; cannot be instantiated

class Square extends Shape {
    double side;
}
// error: Square is not abstract and does not override abstract method area() in Shape

The second error is the important one. In a big code base, someone adding a new subclass months later can't forget to implement area(); the build fails until they do. With the "return 0 and hope it's overridden" approach, the bug would surface only as wrong numbers at run time.

A few combinations are illegal because they contradict each other:

Combination Allowed? Why
abstract + private method No A private method can't be overridden, so it could never get a body.
abstract + static method No Static methods aren't dispatched on an object, so there's nothing to override.
abstract + final (class or method) No final forbids exactly the subclassing/overriding that abstract requires.
abstract method in a non-abstract class No Any class with an abstract method must itself be abstract.
abstract class with no abstract methods Yes Useful when a class is only a shared base and should never be created on its own.
abstract class with fields, constructors, static members Yes It's still a class; it just can't be instantiated directly.

Abstract methods may be public, protected or package-private. When a subclass overrides one, it can keep the same access level or make it wider, but not narrower, just like any override.

Abstract classes can have state and constructors

An abstract class is a full class with one restriction. It can hold fields, enforce rules in a constructor and offer helper methods. Its constructor runs whenever a subclass object is created, through the super(...) call (see The super Keyword). This lets the base class own the invariants that every subclass shares.

Abstract classes can also form chains. A middle class may implement some abstract methods and leave others, staying abstract itself:

Java State, constructors and a chain of abstract classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The name check lives in exactly one place, Employee's constructor, and every kind of employee gets it for free. Making that constructor protected documents that only subclasses are meant to call it. A public constructor in an abstract class isn't wrong, but it's misleading, since nobody outside the hierarchy can use it anyway.

Staff implements kind() but not monthlyPay(), so it stays abstract. Its two subclasses only have to supply the pay calculation.

The template method pattern

The most important use of abstract classes is the template method pattern. The base class defines an algorithm as a fixed sequence of steps in one method (the template), and subclasses fill in some of the steps. The order of steps can't be broken, because it lives in one place and is often marked final.

There are usually two kinds of steps:

  • Abstract steps, which every subclass must provide.
  • Hooks, concrete methods with a default (often empty) body that subclasses may override.
Java A report exporter built with a template method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The exporters never loop, never add up totals and never decide the order of output; the template does. Each subclass contains only what makes it different. Because export is final, no subclass can accidentally skip the header or compute totals another way. Sale here is a record, a compact data class you'll meet properly soon, and the exporters are nested classes so the whole example fits in one file.

You'll find template methods all over the JDK and in frameworks. java.io.InputStream declares one abstract method, read(), and builds read(byte[], int, int), readAllBytes() and skip() on top of it. AbstractList asks you for only get(int) and size() and gives you iteration, indexOf, contains, equals, hashCode and more.

When you see a JDK class named AbstractSomething (AbstractList, AbstractMap, AbstractCollection), it's a skeletal implementation: extend it, implement a couple of methods, and you get a full-featured collection.

A trap: calling overridable methods from a constructor

An abstract class's constructor runs before the subclass's fields are initialized. If that constructor calls an abstract (or any overridable) method, the subclass's override runs on a half-built object:

Java An override running too early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first render() prints [null], even though text is final and is assigned a value. When Widget() runs, Greeting's constructor body hasn't happened yet, so text still holds its default value, null. With an int field you'd see 0; with a method that calls text.length() you'd get a NullPointerException.

The fix is a rule professionals follow strictly: constructors should not call methods that subclasses can override. If the base class needs a setup step, let callers invoke it after construction, or make the helper private or final.

Anonymous subclasses

Sometimes you need a one-off implementation of an abstract class, used in a single place. Instead of naming a new class, you can write an anonymous class right where you create the object:

Java
Shape unitSquare = new Shape() {
    @Override
    double area() {
        return 1.0;
    }
};

This looks like new Shape(), but the braces create a nameless subclass and instantiate that. Nested, Inner, Local and Anonymous Classes covers anonymous classes in detail, including when a lambda is the better choice.

Abstract or concrete? Abstract class or interface?

Choose an abstract class when:

  • The type is a general idea that should never exist on its own (Shape, Employee, ReportExporter).
  • Subclasses share real state or code: fields, constructor checks, helper methods.
  • You want a template method that fixes the order of steps.

Keep a class concrete when it makes sense to create plain instances of it, even if subclasses exist. ArrayList is concrete and can still be extended.

Java offers a second tool for abstraction, the interface, which describes what a type can do without any instance fields. A class can extend only one abstract class but implement many interfaces. In modern Java the usual design is an interface for the public contract, plus an optional abstract class that implements it and provides shared code. The next lesson compares the two in detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given abstract class Animal { abstract String sound(); }, which line compiles?

    You can't instantiate an abstract class, but you can create an array whose elements have the abstract type (all null at first). abstract can't be combined with static or final.
  2. 2. class Dog extends Animal {} with no methods fails to compile. What are your options?

    A concrete subclass must implement every inherited abstract method. If it can't yet, it must be declared abstract itself and leave the job to its own subclasses.
  3. 3. An abstract class's constructor calls an abstract method render(), and the subclass's render() prints a String field set in the subclass constructor. What is printed during construction?

    The superclass constructor runs before the subclass constructor body, so the override sees the field's default value. Avoid calling overridable methods from constructors.
  4. 4. In the template method pattern, why is the template method often declared final?

    The template fixes the sequence of steps in one place. Subclasses customize individual steps (abstract methods and hooks), not the overall flow.
  5. 5. Which statement about abstract classes is true?

    An abstract class is a full class that just can't be instantiated directly. Its constructor runs through super(...) when a subclass object is created.

Summary

  • Abstraction means exposing what a type does while hiding how; code that uses the abstraction doesn't depend on the details.
  • An abstract class can't be instantiated; an abstract method has no body and must be implemented by every concrete subclass.
  • The compiler enforces the rules: a concrete subclass that misses an abstract method doesn't compile. abstract can't be combined with private, static or final.
  • Abstract classes can have fields, constructors (best made protected), concrete methods and static members, and can extend other abstract classes.
  • The template method pattern puts a fixed algorithm in the base class and lets subclasses fill in abstract steps and optional hooks.
  • Don't call overridable methods from constructors: the override runs before the subclass's fields are set.

Next: Interfaces, the other way to define abstractions, with multiple inheritance of type and default methods.