DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

How Java separates interface from implementation

How Java separates interface from implementation

A SavingsAccount and a CheckingAccount both need a close() operation. The behavior differs. One calculates final interest, the other clears overdraft protection. What they share is the guarantee that close() exists and can be called on any account type.

Java gives you two ways to express that guarantee: abstract classes and interfaces.

Abstract classes

An abstract class is a class that cannot be instantiated directly. It can declare abstract methods, methods with a signature but no body, that subclasses must implement.

public abstract class Account {
    protected final String id;
    protected int balance;

    protected Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
    }

    public abstract void close(); // subclasses must implement this

    public void deposit(int amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    public int getBalance() { return balance; }
}

Enter fullscreen mode Exit fullscreen mode

Account provides shared state (id, balance), a shared constructor, and shared methods (deposit, getBalance). It declares close() as abstract, meaning: every concrete subclass must provide an implementation.

public class SavingsAccount extends Account {
    private double interestRate;

    public SavingsAccount(String id, int balance, double rate) {
        super(id, balance);
        this.interestRate = rate;
    }

    @Override
    public void close() {
        applyInterest();
        System.out.println("Savings account " + id + " closed with balance " + balance);
    }

    private void applyInterest() {
        balance += (int)(balance * interestRate);
    }
}

Enter fullscreen mode Exit fullscreen mode

If a class extends an abstract class but does not implement every abstract method, it must itself be declared abstract.

Interfaces

An interface declares a contract: a set of method signatures that implementing classes agree to provide.

public interface Closeable {
    void close();
}

public interface Auditable {
    String auditTrail();
}

Enter fullscreen mode Exit fullscreen mode

A class implements an interface with implements. It can implement multiple interfaces:

public class SavingsAccount extends Account implements Closeable, Auditable {

    @Override
    public void close() {
        // ...
    }

    @Override
    public String auditTrail() {
        return "Account " + id + ": " + balance;
    }
}

Enter fullscreen mode Exit fullscreen mode

Before Java 8, interface methods were always abstract, with no implementation and no state. Since Java 8, interfaces can have default methods (a method body prefixed with default) and static methods.

public interface Closeable {
    void close();

    default boolean isClosed() {
        return false; // subclasses can override or use this default
    }
}

Enter fullscreen mode Exit fullscreen mode

Default methods exist so that methods can be added to widely-used interfaces without breaking every existing implementation. java.util.Collection gained stream() and forEach() as default methods in Java 8 without requiring all implementations to change.

Interfaces still cannot hold instance state. Interface fields are implicitly public static final. They are constants, not per-instance data.

Multiple inheritance with interfaces

A class can implement any number of interfaces. It can extend at most one class. This is Java's answer to multiple inheritance: you can share contracts freely across the type hierarchy, but you can only inherit implementation from one class at a time.

If two interfaces declare a default method with the same signature, the implementing class must override the method and choose which one to call (or provide its own):

interface A {
    default String name() { return "A"; }
}

interface B {
    default String name() { return "B"; }
}

class C implements A, B {
    @Override
    public String name() { return A.super.name(); } // explicitly pick A's default
}

Enter fullscreen mode Exit fullscreen mode

Functional interfaces

An interface with exactly one abstract method is a functional interface. Java 8 introduced the @FunctionalInterface annotation to signal intent and have the compiler enforce the one-method constraint.

@FunctionalInterface
public interface Validator<T> {
    boolean validate(T value);
}

Enter fullscreen mode Exit fullscreen mode

Functional interfaces are the foundation for lambda expressions, covered in the functional programming articles. Any place that expects a Validator<Account> can accept a lambda account -> account.getBalance() >= 0 without defining a named class.

The java.util.function package defines a standard library of functional interfaces: Predicate<T>, Function<T, R>, Consumer<T>, Supplier<T>, and their primitives and variations.

Sealed interfaces and classes

Java 17 introduced sealed types. A sealed class or interface restricts which classes may extend or implement it.

public sealed interface Shape permits Circle, Rectangle, Triangle {}

public record Circle(double radius) implements Shape {}
public record Rectangle(double width, double height) implements Shape {}
public record Triangle(double base, double height) implements Shape {}

Enter fullscreen mode Exit fullscreen mode

The permits clause names the only allowed implementations. No other class can implement Shape. The compiler and reader both know that Circle, Rectangle, and Triangle are the complete set.

Sealed types pair well with pattern matching in switch expressions. The compiler can verify that a switch on a Shape covers all cases:

double area = switch (shape) {
    case Circle c -> Math.PI * c.radius() * c.radius();
    case Rectangle r -> r.width() * r.height();
    case Triangle t -> 0.5 * t.base() * t.height();
};

Enter fullscreen mode Exit fullscreen mode

No default case is needed. The compiler knows the three records are exhaustive.

Choosing between abstract class and interface

Both let you define a type that callers can program against. The difference comes down to what you need to share.

Use an abstract class when:

  • Subclasses need to share state (fields)
  • Subclasses need to share constructor logic via super()
  • Some methods have a common implementation that is not safe to make a default

Use an interface when:

  • You are defining a capability that unrelated classes can share (Comparable, Iterable, Closeable)
  • A class needs to satisfy multiple contracts simultaneously
  • You have no state to share

If a class needs both shared state and multiple contracts, extend one abstract class and implement the remaining contracts as interfaces. That is the most common pattern in the Java standard library. ArrayList, for example, extends AbstractList (which provides shared list behaviour) and implements List, RandomAccess, Cloneable, and Serializable.

Prediction exercise

interface Printable {
    void print();

    default String prefix() { return "[INFO]"; }
}

abstract class Document implements Printable {
    protected String content;

    Document(String content) { this.content = content; }

    @Override
    public String prefix() { return "[DOC]"; }
}

class Report extends Document {
    Report(String content) { super(content); }

    @Override
    public void print() {
        System.out.println(prefix() + " " + content);
    }
}

Printable p = new Report("Q3 results");
p.print();

Enter fullscreen mode Exit fullscreen mode

Predict the output. Then: if you remove the prefix() override in Document, what changes?

Top comments (0)