The <code>abstract</code> Keyword in Java

abstract marks a class or method as incomplete. An abstract class can't be instantiated directly; an abstract method has no body and must be overridden by a concrete subclass. It's Java's way of saying "here's a partial implementation β€” complete it".

Abstract class

public abstract class Shape {
    private final String id = UUID.randomUUID().toString();
    public String id() { return id; }                 // concrete
    public abstract double area();                     // abstract β€” each subclass provides
}

new Shape();                                          // ❌ compile error

public class Circle extends Shape {
    private final double r;
    public Circle(double r) { this.r = r; }
    @Override public double area() { return Math.PI * r * r; }
}

Abstract method rules

  • No body (ends with ;, not {}).
  • Must be declared in an abstract class (or interface).
  • Cannot be private, static, or final β€” those contradict "must be overridden".

Abstract class vs interface

abstract classinterface
Multiple inheritanceNoYes
Instance fieldsYesOnly constants
ConstructorsYesNo
Partial implementationYesDefault methods only (Java 8+)
Typical useShared state + behaviourPure contract

Template method pattern

Abstract classes shine when most of a workflow is the same across subclasses but certain steps vary:

public abstract class Exporter {
    public final void export(Data d) {                 // final β€” subclasses don't change the order
        open();
        writeHeader();
        writeBody(d);                                   // step varies per subclass
        close();
    }
    protected abstract void writeBody(Data d);

    protected void open()        { ... }               // shared default
    protected void writeHeader() { ... }
    protected void close()        { ... }
}

Common mistakes

  • Abstract class with one subclass β€” usually just a regular class.
  • Protected fields β€” breaks encapsulation. Use protected methods.
  • Forcing inheritance for reuse β€” if the is-a relationship is weak, prefer composition.

Related

Pillar: Java keywords. See also abstraction, interfaces, inheritance.