Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Abstract Classes in Java: Interfaces and Composition
Abstract classes let related classes share state or implementation while leaving selected methods for subclasses to define.
Introduction
An abstract class can hold instance fields, constructors, concrete methods, and abstract methods. Java interfaces can also provide behavior through default methods, but they cannot hold instance state or define constructors. The choice depends on what the types need to share and how tightly they should be related.
This guide compares interfaces, abstract classes, and composition with a notification example. It also covers the Template Method pattern, sealed types in Java 17 and later, and a constructor hazard: an override can run before the subclass’s fields have been initialized.
When to use
Consider an abstract class when:
- Related classes need the same instance state or constructor validation.
- A shared algorithm should call subclass-specific steps in a fixed order.
- A base class can enforce an invariant that every subclass must follow.
public abstract class Notification {
// Concrete method: shared implementation
protected final void log(String message) {
System.out.println("[NOTIFICATION] " + message);
}
// Abstract method: subclasses implement this
public abstract void send(String recipient, String content);
// Concrete method using abstract method
public void notifyUser(String recipient, String content) {
log("Sending to " + recipient);
send(recipient, content); // Calls subclass implementation
log("Sent successfully");
}
}
public class EmailNotification extends Notification {
@Override
public void send(String recipient, String content) {
System.out.println("EMAIL to " + recipient + ": " + content);
}
}
public class SmsNotification extends Notification {
@Override
public void send(String recipient, String content) {
System.out.println("SMS to " + recipient + ": " + content);
}
}
When to consider another design
An abstract class adds coupling through the superclass relationship. Consider another design when:
- Unrelated classes need a common type. An interface lets each class implement the contract while extending a different class.
- The shared behavior is small and stateless. An interface
defaultmethod may be enough. - A feature should be added, replaced, or combined independently. A composed helper or delegate keeps that choice out of the inheritance tree.
- There is only one implementation and no useful shared contract or state. A concrete class may be simpler.
// Avoid a base class with no shared state or behavior.
public abstract class BaseThing {
protected void commonMethod() { }
}
public class OnlyUse extends BaseThing { }
// An abstract class can enforce a shared parsing sequence.
public abstract class Parser {
// Common structure all parsers follow
public final ParseResult parse(String input) {
validate(input);
return doParse(input);
}
private void validate(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Input cannot be empty");
}
}
// Subclasses implement this
protected abstract ParseResult doParse(String input);
}
Choosing among an interface, abstract class, and composition
Suppose email and SMS notifiers both send a message, and some deployments also need logging. Here are three reasonable designs for that same problem:
| Choice | Notification design | Trade-off |
|---|---|---|
| Interface | Notifier declares send; a default notifyUser method can provide a small shared flow. |
Any class can implement the contract, but the interface cannot keep a per-notifier logger or channel field. |
| Abstract class | AbstractNotifier stores a channel, validates it in its constructor, and owns a final notifyUser template. |
Shared state and an enforced sequence are easy to express, but a notifier can extend only one class. |
| Composition | LoggingNotifier wraps another Notifier and logs before delegating to send. |
Logging can be added or replaced independently, with an extra wrapper and delegation step. |
interface Notifier {
void send(String recipient, String message);
default void notifyUser(String recipient, String message) {
send(recipient, message);
}
}
abstract class AbstractNotifier implements Notifier {
private final String channel;
protected AbstractNotifier(String channel) {
if (channel == null || channel.isBlank()) {
throw new IllegalArgumentException("channel is required");
}
this.channel = channel;
}
protected final String channel() {
return channel;
}
@Override
public final void notifyUser(String recipient, String message) {
System.out.println("Sending through " + channel);
send(recipient, message);
}
}
final class LoggingNotifier implements Notifier {
private final Notifier delegate;
LoggingNotifier(Notifier delegate) {
this.delegate = delegate;
}
@Override
public void send(String recipient, String message) {
System.out.println("Sending to " + recipient);
delegate.send(recipient, message);
}
}
Start with an interface when callers need a contract across different types. Use an abstract class when shared state or a fixed algorithm belongs to the base type. Use composition when the extra behavior should remain optional or swappable. These are trade-offs, not rules based only on the number of methods.
Java 17 added sealed classes and interfaces as a way to declare a known set of direct subtypes. A sealed type is useful when the model has a deliberately closed set of variants; it is not a security boundary. Each permitted subtype must be declared final, sealed, or non-sealed. The current Java SE 27 specification describes the rules for sealed classes and sealed interfaces.
sealed interface Payment permits CardPayment, CashPayment { }
record CardPayment(String reference) implements Payment { }
final class CashPayment implements Payment { }
This Java 17 example permits exactly two direct variants. A record is implicitly final, and CashPayment is explicitly final, so both satisfy the sealed type’s subtype rules.
Abstract class architecture
classDiagram
class Notification {
+log(message) void
+send(recipient, content) void$abstract
+notifyUser(recipient, content) void
}
class EmailNotification {
+send(recipient, content) void
}
class SmsNotification {
+send(recipient, content) void
}
class PushNotification {
+send(recipient, content) void
}
Notification <|-- EmailNotification
Notification <|-- SmsNotification
Notification <|-- PushNotification
note for Notification "abstract: cannot be instantiated\nsend(): no implementation"
Failure scenarios
1. Trying to instantiate an abstract class
The compiler rejects new Shape(). Assigning the result to a variable of type Shape does not change that; abstract classes cannot be instantiated.
An abstract class may have abstract methods, concrete methods, or no abstract methods at all. The abstract modifier still prevents direct instantiation.
Use the abstract type as the variable type and create a concrete subclass. The example uses an abstract class named Shape, not an interface.
public abstract class Shape {
public abstract double area();
}
// Does not compile
Shape s = new Shape(); // Error: Cannot instantiate abstract class
// Correct usage
Shape s = new Circle(5);
2. Forgetting to implement abstract methods
When a concrete class extends an abstract class, it must implement every inherited abstract method. Otherwise, the compiler rejects it. An incomplete subclass can remain abstract and pass those requirements to a later subclass.
The same requirement applies when an abstract class implements an interface but leaves one of its methods unimplemented. Every concrete subclass must eventually provide that method.
public abstract class Base {
public abstract void doSomething();
}
// Does not compile: all abstract methods must be implemented
public class Incomplete extends Base {
// Missing @Override doSomething()
}
// Fix: implement all abstract methods or declare class abstract
public class Complete extends Base {
@Override
public void doSomething() {
System.out.println("Done!");
}
}
3. Calling abstract methods from a constructor
This code compiles, but the override runs before the subclass’s field initializers. Java first assigns default values to the object’s fields, calls the superclass constructor, and only then runs the subclass’s field initializers. So the override sees 0 for an int field or null for a reference field. A NullPointerException occurs only if the override dereferences a reference that is still null.
abstract class Base {
private final int valueSeenDuringConstruction;
Base() {
valueSeenDuringConstruction = value();
}
protected abstract int value();
int valueSeenDuringConstruction() {
return valueSeenDuringConstruction;
}
}
final class Derived extends Base {
private final int value = 10;
@Override
protected int value() {
return value;
}
}
public class ConstructorDispatchDemo {
public static void main(String[] args) {
Derived derived = new Derived();
if (derived.valueSeenDuringConstruction() != 0 || derived.value() != 10) {
throw new AssertionError("Unexpected initialization order");
}
System.out.println("during super(): 0; after construction: 10");
}
}
Save this as ConstructorDispatchDemo.java, then run javac ConstructorDispatchDemo.java && java ConstructorDispatchDemo. The example prints during super(): 0; after construction: 10. The Java SE 27 specification documents this dispatch order in §12.5, Creation of New Class Instances.
Trade-off table
| Feature | Abstract class | Interface |
|---|---|---|
| Behavior | Can define concrete and abstract methods. | Can define abstract, default, and static methods; private helper methods are supported from Java 9. |
| State | Can hold instance fields and initialize them in a constructor. | No instance fields or constructors; interface fields are public static final constants. |
| Inheritance | A class can extend one class. | A class can implement multiple interfaces. |
| Best fit | Related types that share state, invariants, or a template algorithm. | A contract shared by types that do not need a common class parent. |
Code snippets
Template Method pattern
The Template Method pattern fits when subclasses need different steps but must follow the same sequence. Put that sequence in a final method, then let subclasses implement the parts that vary.
Here, process() fetches, cleans, analyzes, and saves data. Subclasses provide the fetch, analysis, and save steps; the base class supplies clean().
public abstract class DataProcessor {
// Template method: defines the algorithm skeleton
public final void process(String dataSource) {
String rawData = fetchData(dataSource);
String cleanedData = clean(rawData);
Object result = analyze(cleanedData);
save(result);
}
// Steps to be implemented by subclasses
protected abstract String fetchData(String source);
protected abstract Object analyze(String data);
protected abstract void save(Object result);
// Shared implementation; subclasses may override it
protected String clean(String raw) {
return raw.trim().toLowerCase();
}
}
public class CloudDataProcessor extends DataProcessor {
@Override
protected String fetchData(String source) {
return cloudClient.download(source);
}
@Override
protected Object analyze(String data) {
return new MLModel(data).predict();
}
@Override
protected void save(Object result) {
database.store(result);
}
}
Abstract class with a protected helper
Another pattern is to keep the public methods in the abstract class and delegate storage operations to protected abstract methods. The shared methods can handle checks, while subclasses choose how to store the data.
The Queue<T> example below uses an abstract class to keep checks in one place while subclasses supply storage operations. An interface can also share stateless method bodies through default methods, but it cannot own per-instance queue state. Composition is another option when storage should be a replaceable helper rather than a superclass responsibility.
public abstract class Queue<T> {
// Abstract methods: subclasses implement storage
protected abstract void enqueueInternal(T item);
protected abstract T dequeueInternal();
protected abstract boolean isEmptyInternal();
protected abstract int sizeInternal();
// Concrete methods using abstract primitives
public void enqueue(T item) {
if (item == null) {
throw new IllegalArgumentException("Cannot enqueue null");
}
enqueueInternal(item);
}
public T dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return dequeueInternal();
}
public boolean isEmpty() {
return isEmptyInternal();
}
public int size() {
return sizeInternal();
}
}
Design notes
- Sealed classes and interfaces (Java 17+) express a deliberately closed set of direct subtypes. Use them to model a finite set of variants, not as a security boundary.
- A constructor should not call a method that a subclass can override. Subclass fields still hold default values at that point.
- Mark concrete methods
finalwhen subclasses must not change their behavior. - If you expose protected fields, document the invariants subclasses must preserve.
Pitfalls
- A method in a class cannot omit its body unless it is declared
abstract. - Calling an overridable method from a constructor can expose default-valued subclass fields.
- If the base class accumulates many abstract methods, split the contract or use interfaces.
- If one concrete class is the only user of a base class, see whether the extra type helps.
- Deep inheritance trees couple subclasses to their ancestors; composition can reduce that coupling.
// An interface is enough when the type only needs to declare a contract.
interface Serializer {
void serialize();
}
// Good: abstract class with shared implementation
public abstract class LoggingBean {
protected Logger logger = Logger.getLogger(getClass());
protected void logInfo(String msg) { logger.info(msg); }
protected void logError(String msg, Exception e) { logger.error(msg, e); }
// Subclasses implement business logic
public abstract void doSomething();
}
Quick recap checklist
- Use an abstract class when related types need shared instance state, invariants, or a fixed algorithm.
- Use an interface for a shared contract; a
defaultmethod can cover small stateless behavior. - Use composition when behavior should be optional or replaceable.
- Keep overridable calls out of constructors so subclass state is initialized before use.
- For a sealed type, make each permitted subtype
final,sealed, ornon-sealed.
Interview questions
Further reading
- Polymorphism in Java explains dispatch through a shared type.
- Interfaces in Java covers contracts and default methods.
- Composition over Inheritance discusses delegation as an alternative to a superclass.
- Oracle: Abstract Methods and Classes explains abstract class usage.
- Java SE 27 Language Specification, Chapter 9 defines interface methods and sealed interfaces.
- Java SE 27 Language Specification, Chapter 8 defines classes and sealed subclasses.
Conclusion
Choose an abstract class when related types need shared instance state, constructor checks, or an algorithm that subclasses must follow. Interfaces can express the shared contract and can provide small default methods, while composition keeps optional behavior outside the superclass tree.
The Template Method pattern fits when every subclass should follow the same sequence but supply different steps. A final method owns that sequence and calls protected methods that subclasses implement.
An abstract class cannot be instantiated directly, but its constructor runs as part of each subclass construction. Avoid calling overridable methods from that constructor: Java dispatches to the subclass override before the subclass field initializers have run.
Sealed classes and interfaces, available since Java 17, let a type declare a known set of direct subtypes. Use them when the domain has a fixed set of variants, such as payment forms, and keep security decisions separate from that modeling choice.
An abstract type gives callers a common reference for polymorphism. See Polymorphism in Java for runtime dispatch and Interfaces in Java for contracts a class can implement alongside its one superclass.
Category
Related Posts
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.
ArrayList in Java
Compare ArrayList's Java SE 27 contract with OpenJDK 27 growth behavior, capacity hints, operation costs, fail-fast iterators, and bounded concurrency options.