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
abstractclass (or interface). - Cannot be
private,static, orfinalβ those contradict "must be overridden".
Abstract class vs interface
| abstract class | interface | |
|---|---|---|
| Multiple inheritance | No | Yes |
| Instance fields | Yes | Only constants |
| Constructors | Yes | No |
| Partial implementation | Yes | Default methods only (Java 8+) |
| Typical use | Shared state + behaviour | Pure 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.