Java Abstraction
Abstraction means showing what something does while hiding how it does it. When you call list.sort() you don't care which sorting algorithm runs; you only care that the list ends up sorted. In Java, abstraction is expressed with abstract classes and interfaces. This chapter covers abstract classes; interfaces follow in the next one.
Abstract classes and methods
An abstract class is a class that is deliberately incomplete:
- It cannot be instantiated with
new. - It may contain abstract methods — methods declared without a body, ending in
;. - It may also contain ordinary fields, constructors and fully implemented methods.
- A concrete (non-abstract) subclass must implement every abstract method.
abstract class Shape {
private final String name;
Shape(String name) {
this.name = name;
}
abstract double area(); // no body: each shape knows its own formula
abstract double perimeter();
void describe() { // a normal method using the abstract ones
System.out.printf("%-9s area=%7.2f perimeter=%6.2f%n", name, area(), perimeter());
}
}
class Circle extends Shape {
private final double r;
Circle(double r) { super("Circle"); this.r = r; }
@Override double area() { return Math.PI * r * r; }
@Override double perimeter() { return 2 * Math.PI * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { super("Rectangle"); this.w = w; this.h = h; }
@Override double area() { return w * h; }
@Override double perimeter() { return 2 * (w + h); }
}
class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(1.5), new Rectangle(4, 2.5) };
for (Shape s : shapes) {
s.describe();
}
// Shape s = new Shape("blob"); // error: Shape is abstract; cannot be instantiated
}
}Circle area= 7.07 perimeter= 9.42
Rectangle area= 10.00 perimeter= 13.00
describe() is written once in Shape and works for every shape, because it relies only on the abstract contract (area() and perimeter()).
Forgetting to implement
If a subclass doesn't implement all abstract methods, it must itself be declared abstract — otherwise the code won't compile:
class Triangle extends Shape {
Triangle() { super("Triangle"); }
double area() { return 0; }
}
// error: Triangle is not abstract and does not override abstract method perimeter() in ShapeThe template method pattern
A powerful use of abstract classes is to fix the overall steps of an algorithm in the parent, while letting subclasses fill in individual steps. This is called the template method pattern:
abstract class Report {
// the template: the order of steps is fixed and final
final void generate() {
System.out.println("=== " + title() + " ===");
body();
System.out.println("--- generated by ReportEngine ---");
}
abstract String title();
abstract void body();
}
class SalesReport extends Report {
@Override String title() { return "Sales Q3"; }
@Override void body() {
System.out.println("Units sold: 1,240");
System.out.println("Revenue: 86,800 EUR");
}
}
class InventoryReport extends Report {
@Override String title() { return "Inventory"; }
@Override void body() {
System.out.println("Items below minimum stock: 3");
}
}
class Main {
public static void main(String[] args) {
new SalesReport().generate();
new InventoryReport().generate();
}
}=== Sales Q3 ===
Units sold: 1,240
Revenue: 86,800 EUR
--- generated by ReportEngine ---
=== Inventory ===
Items below minimum stock: 3
--- generated by ReportEngine ---
Making generate() final guarantees no subclass can change the order of the steps.
Abstraction in the standard library
You use abstractions every day:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Main {
static int total(List<Integer> numbers) { // works with ANY List implementation
int sum = 0;
for (int n : numbers) sum += n;
return sum;
}
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(List.of(1, 2, 3));
List<Integer> b = new LinkedList<>(List.of(10, 20));
System.out.println(total(a));
System.out.println(total(b));
Number n = 42; // Number is an abstract class
System.out.println(n.doubleValue());
}
}6
30
42.0
List is an interface, and Number (the parent of Integer, Double, ...) is an abstract class. Code written against these abstractions doesn't depend on the concrete implementation.
| Abstract class | Concrete class | |
|---|---|---|
new allowed |
no | yes |
| Abstract methods | allowed | not allowed |
| Constructors | yes (called via super) |
yes |
| Fields and normal methods | yes | yes |
Tip: Use an abstract class when related classes share state or code (fields, constructors, helper methods). When you only need to describe a capability, prefer an interface.
Test yourself
Can you create an object with new from an abstract class?
- Yes
- No
- Only if it has a constructor
- Only inside the same package
How is an abstract method declared?
- abstract void draw() {}
- abstract void draw();
- void draw() = 0;
- void abstract draw;
A subclass of an abstract class doesn't implement one abstract method. What must be true?
- Nothing, it compiles
- The subclass must also be abstract
- The method is inherited empty
- It throws at runtime