OOP Abstraction
Abstract Methods and Classes
An abstract method has a signature but no body, and is marked abstract. A class that contains one must itself be declared abstract, and it cannot be instantiated with new. A concrete subclass must implement every inherited abstract method, or be abstract too.
The Rules
- An abstract class may have fields, constructors and concrete methods, like any class; its constructors run when a subclass is created.
- An abstract method cannot be
private,staticorfinal, because each of those prevents a subclass from implementing it. - A class may be abstract even with no abstract methods, simply to forbid direct instances.
The Template Method Pattern
Abstract classes shine when several classes share an algorithm but differ in one step. The abstract class implements the algorithm in a concrete method and leaves the varying step abstract. Below, describe() is written once and calls area(), which each shape supplies.
// An abstract class defines a template; subclasses supply the missing parts.
import java.util.List;
abstract class Shape {
private final String name;
protected Shape(String name) { this.name = name; }
abstract double area(); // no body: every subclass must implement it
// A concrete method that relies on the abstract one (template method pattern).
String describe() {
return String.format("%s with area %.2f", name, area());
}
}
class Circle extends Shape {
private final double r;
Circle(double r) { super("circle"); this.r = r; }
@Override double area() { return Math.PI * r * 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; }
}
class Shapes {
public static void main(String[] args) {
// Shape s = new Shape("x"); // error: Shape is abstract
List<Shape> shapes = List.of(new Circle(1), new Rectangle(2, 3));
double total = 0;
for (Shape s : shapes) { // one loop, many implementations
System.out.println(s.describe());
total += s.area();
}
System.out.printf("total area %.2f%n", total);
}
}
Output:
circle with area 3.14
rectangle with area 6.00
total area 9.14
Polymorphism
The loop above treats circles and rectangles alike through the type Shape, and each call to area() runs the right implementation (dynamic dispatch, introduced in Inheritance). Code written against an abstraction keeps working when new implementations appear: adding a Triangle requires no change to the loop.
Program to an Abstraction
The same idea organizes larger programs. The checkout method below accepts any PaymentMethod; it neither knows nor cares whether it is talking to a card or a voucher. The workflow in pay() is final, so subclasses can change how authorization works but not the order of steps.
// Program to an abstraction: the checkout depends only on the abstract type.
abstract class PaymentMethod {
abstract boolean authorize(double amount);
final String pay(double amount) { // final: subclasses cannot change the workflow
return authorize(amount) ? "paid " + amount : "declined " + amount;
}
}
class Card extends PaymentMethod {
private final double limit;
Card(double limit) { this.limit = limit; }
@Override boolean authorize(double amount) { return amount <= limit; }
}
class Voucher extends PaymentMethod {
private double credit;
Voucher(double credit) { this.credit = credit; }
@Override boolean authorize(double amount) {
if (amount > credit) return false;
credit -= amount;
return true;
}
}
class Payments {
static void checkout(PaymentMethod method, double amount) {
System.out.println(method.getClass().getSimpleName() + ": " + method.pay(amount));
}
public static void main(String[] args) {
checkout(new Card(500), 120.0);
checkout(new Card(100), 120.0);
Voucher v = new Voucher(50);
checkout(v, 30.0);
checkout(v, 30.0); // only 20 credit left
}
}
Output:
Card: paid 120.0
Card: declined 120.0
Voucher: paid 30.0
Voucher: declined 30.0
Declare variables, parameters and return types with the most abstract type that offers what you need — List rather than ArrayList, PaymentMethod rather than Card. This keeps callers independent of implementation choices, and makes code easy to test with simple stand-in implementations.
Abstract Class or Interface?
Interfaces, covered in their own lesson Interfaces, are the other abstraction tool. Since Java 8 they may contain default and static methods, so the two overlap; the differences that remain decide the choice.
Comparison
| Aspect | Abstract class | Interface |
|---|---|---|
| A class can extend / implement | one | many |
| Instance fields (state) | yes | no (only constants) |
| Constructors | yes | no |
| Method bodies | any | default, static and private methods |
| Member visibility | any | public (except private helpers) |
| Best for | a family of closely related classes sharing state and code | a capability that unrelated classes can offer |
A Practical Rule
Start with an interface: it describes a role (Comparable, Runnable, PaymentMethod) without constraining the implementing class's hierarchy. Add an abstract class when implementations genuinely share state or a fixed workflow — often as a convenience base that implements the interface, as the JDK's AbstractList does for List. To fix the complete set of implementations, make the interface sealed.
Practice
Exercises
- Add a
Triangleshape (three sides, Heron's formula) and confirm the loop inmainneeds no change. - Turn
PaymentMethodinto an interface with adefaultpaymethod. What can no longer be expressed, and why isfinallost? - Write a
FakePaymentthat always approves, and use it to testcheckoutwithout real cards or vouchers.