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.

published: reading time: 17 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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 default method 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 final when subclasses must not change their behavior.
  • If you expose protected fields, document the invariants subclasses must preserve.

Pitfalls

  1. A method in a class cannot omit its body unless it is declared abstract.
  2. Calling an overridable method from a constructor can expose default-valued subclass fields.
  3. If the base class accumulates many abstract methods, split the contract or use interfaces.
  4. If one concrete class is the only user of a base class, see whether the extra type helps.
  5. 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 default method 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, or non-sealed.

Interview questions

1. What is an abstract class in Java?
An abstract class is a class marked with the `abstract` keyword that cannot be instantiated directly. It serves as a base type for subclasses and may contain abstract methods (methods without implementation) that subclasses must implement, concrete methods (with implementation) that are shared across subclasses, or both.
2. What is the difference between an abstract class and an interface?
An abstract class can have constructors, instance fields, and concrete or abstract methods. An interface has no instance fields or constructors, but it can declare abstract, default, and static methods. A class can implement several interfaces but extend only one class.
3. Can an abstract class have a constructor?
Yes. A superclass constructor runs when a subclass is created, through an explicit `super(...)` call or the compiler's implicit no-argument call. It can initialize shared fields and check invariants.
4. Can an abstract class be sealed in Java?
Yes. Since Java 17, a sealed abstract class can list its permitted direct subclasses. Each one must be `final`, `sealed`, or `non-sealed`. Sealed types help model a fixed set of variants; they are not a security boundary.
5. What is the Template Method pattern and how does it relate to abstract classes?
A final method defines the algorithm's steps and calls methods that subclasses implement. Subclasses supply those steps without changing their order.
6. What happens if a subclass doesn't implement all abstract methods?
A concrete subclass must implement every inherited abstract method. Otherwise, it must also be declared `abstract`.
7. Why should abstract methods not be called from constructors?
When a subclass constructor runs, the parent constructor executes first. If the parent constructor calls an abstract method, the subclass override executes before the subclass's own fields are initialized. This means the abstract method runs on a partially constructed object with uninitialized fields.
8. What is the difference between abstract class and concrete class?
A concrete class can be instantiated with `new`. An abstract class cannot; it may leave abstract methods for a concrete subclass to implement.
9. Can an abstract class extend a concrete class?
Yes. It inherits the concrete class's behavior and may add abstract methods that its concrete subclasses must implement.
10. When should you prefer an abstract class over an interface?
Use one when related subclasses need shared state, constructor checks, or a fixed algorithm. Choose an interface when a common contract matters more than a shared class parent.
11. Can an abstract class implement an interface?
Yes, an abstract class can implement an interface and need not implement all of its methods. The abstract class can leave some interface methods unimplemented, and concrete subclasses of the abstract class must implement them. This is a common pattern for providing partial implementation of a contract.
12. What is a concrete subclass?
A concrete subclass is a class that extends an abstract class and implements all of its abstract methods. Unlike an abstract class, a concrete subclass can be instantiated with `new`. All abstract methods from the parent hierarchy must be implemented for a class to be concrete.
13. Can abstract methods be private in Java?
No, abstract methods cannot be private. If an abstract method were private, subclasses could not override it, which defeats the purpose of being abstract. The abstract method must be accessible to any class that might extend the abstract class and provide an implementation.
14. What is the relationship between abstract classes and the fragile base class problem?
A change to a concrete method or field in the base class can alter subclass behavior. Tests for subclasses help catch unintended effects.
15. Can you declare a class both abstract and final?
No. `abstract` prevents instantiation, while `final` prevents subclassing. Java rejects the combination.
16. How do abstract classes support polymorphism?
A variable of the abstract type can refer to any concrete subclass. Overridden methods dispatch to the implementation on the actual object.
17. What is the difference between abstract class and interface for multiple inheritance?
A class can implement several interfaces but extend only one class. It can extend an abstract class and implement additional interfaces.
18. Can abstract classes have static methods?
Yes, abstract classes can have static methods. Static methods belong to the class, not to instances, so they can be called without an instance. They are not inherited as abstract methods would be, but they are accessible to all subclasses and can be called normally.
19. What is the difference between the Template Method pattern and the Strategy pattern?
Template Method fixes the sequence in a base class and lets subclasses fill in steps. Strategy keeps an algorithm behind an interface so a context can receive a different implementation.
20. How do sealed abstract classes control an inheritance hierarchy?
A sealed abstract class lists its permitted direct subclasses. The compiler rejects other direct subclasses, and each permitted subtype must choose `final`, `sealed`, or `non-sealed`. This is useful when a domain has a fixed set of variants.

Further reading

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals

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.

#java-arraylist #java #java-fundamentals