LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · FOUNDATIONS · 6 OF 48

Interfaces vs Abstract Classes in Java: Differences and How to Choose

When to use an interface and when to use an abstract class, shown with a library system: what each one can hold, default, static and private interface methods, state and constructors in abstract classes, implementing many interfaces, the default method clash and how to resolve it, the interface plus skeleton class combo, and a simple rule for choosing, with Java 17 code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 14

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 199 lines, with a small main() demo. Save it as InterfacesVsAbstractDemo.java, then run javac InterfacesVsAbstractDemo.java && java InterfacesVsAbstractDemo.

import java.util.List;

/**
 * Interfaces vs abstract classes with a small library.
 * Part 1: one fat abstract class forces a magazine to fake abilities it does not have.
 * Part 2: an abstract class for the family (LibraryItem) and interfaces for capabilities
 *         (Borrowable, Reservable), including a default method clash and how to resolve it.
 */
public class InterfacesVsAbstractDemo {

    public static void main(String[] args) {
        // ---------- Part 1: the problem ----------
        FatItem fat = new FatMagazine();
        try {
            fat.loanDays();
        } catch (UnsupportedOperationException e) {
            System.out.println("Fat design: magazine had to throw from loanDays()");
        }

        // ---------- Part 2: the clean version ----------
        Book book = new Book("B-17", "River Maps");
        Ebook ebook = new Ebook("E-04", "Night Trains");
        Magazine magazine = new Magazine("M-88", "Weekly Science");

        for (LibraryItem item : List.of(book, ebook, magazine)) {
            System.out.println(item.label());
        }

        LoanDesk desk = new LoanDesk();
        System.out.println(desk.lend(book, "asha"));
        System.out.println(desk.lend(ebook, "ravi"));
        // desk.lend(magazine, "kim");   // does not compile: Magazine is not Borrowable

        System.out.println("Book late fee, 3 days : " + book.lateFee(3));
        System.out.println("Ebook late fee, 3 days: " + ebook.lateFee(3));

        book.reserve("meena");
        System.out.println("Book reserved for: " + book.reservedFor());
        System.out.println("Book rules: " + book.rules());
    }
}

// ---------- Part 1: the problem ----------

abstract class FatItem {
    abstract int loanDays();

    abstract void reserve(String member);
}

class FatMagazine extends FatItem {
    @Override
    int loanDays() {
        throw new UnsupportedOperationException("reading room only");
    }

    @Override
    void reserve(String member) {
        throw new UnsupportedOperationException("reading room only");
    }
}

// ---------- Part 2: the family ----------

/** What every item IS: shared state, a constructor, finished and abstract methods. */
abstract class LibraryItem {
    private final String id;
    private final String title;

    protected LibraryItem(String id, String title) {
        if (id == null || id.isBlank() || title == null || title.isBlank()) {
            throw new IllegalArgumentException("id and title are required");
        }
        this.id = id;
        this.title = title;
    }

    final String label() {
        return id + " [" + shelf() + "] " + title;
    }

    /** public: it also satisfies Borrowable.title() for every borrowable child. */
    public final String title() {
        return title;
    }

    abstract String shelf();
}

// ---------- Part 2: the capabilities ----------

/** What an item CAN DO: be lent. No state; defaults and statics allowed. */
interface Borrowable {
    String title();

    int loanDays();

    long dailyFine();

    default long lateFee(int daysLate) {
        return Math.max(0, daysLate) * dailyFine();
    }

    default String rules() {
        return "return within " + loanDays() + " days";
    }
}

interface Reservable {
    void reserve(String member);

    default String rules() {
        return "reservations held for 2 days";
    }
}

class Book extends LibraryItem implements Borrowable, Reservable {
    private String reservedFor = "nobody";

    Book(String id, String title) {
        super(id, title);
    }

    @Override
    String shelf() {
        return "stacks";
    }

    @Override
    public int loanDays() {
        return 14;
    }

    @Override
    public long dailyFine() {
        return 5;
    }

    @Override
    public void reserve(String member) {
        reservedFor = member;
    }

    String reservedFor() {
        return reservedFor;
    }

    /** Both interfaces have a default rules(): the class must decide. */
    @Override
    public String rules() {
        return Borrowable.super.rules() + "; " + Reservable.super.rules();
    }
}

class Ebook extends LibraryItem implements Borrowable {
    Ebook(String id, String title) {
        super(id, title);
    }

    @Override
    String shelf() {
        return "digital";
    }

    @Override
    public int loanDays() {
        return 7;
    }

    @Override
    public long dailyFine() {
        return 0;
    }

    /** Overrides the default: an ebook just expires, so there is never a fee. */
    @Override
    public long lateFee(int daysLate) {
        return 0;
    }
}

/** Opts into no capability, so it has nothing to fake. */
class Magazine extends LibraryItem {
    Magazine(String id, String title) {
        super(id, title);
    }

    @Override
    String shelf() {
        return "reading room";
    }
}

/** Depends on the capability, not the family. */
class LoanDesk {
    String lend(Borrowable item, String member) {
        return member + " borrows " + item.title() + " for " + item.loanDays() + " days";
    }
}

Notes

The problem

A first attempt puts everything in one abstract base class: every item has loan days and can be reserved. Then the library adds magazines that never leave the reading room. The magazine class is forced to throw unsupported operation for half its methods, and any code that lends items has to remember which ones blow up. The base class mixed what an item is with what an item can do.

A fat abstract class
abstract class FatItem {
  abstract int loanDays();
  abstract void reserve(String member);
}
class Magazine extends FatItem {
 int loanDays() {
  throw new UnsupportedOperationException();
 }
 void reserve(String m) { throw ... }
}

The idea

Here is the short version. An abstract class is a partly built parent for one family of classes. It shares fields and code, and children extend it. An interface is a capability that any class can sign up for, a contract with no instance state. Every library item has an id, a title and a shelf, so that is the family. Being lendable or reservable are capabilities, so those become interfaces.

In one sentence
  • abstract class = a partly
  • built parent for one family:
  • shared fields and code
  • interface = a capability any
  • class can sign up for:
  • a contract, no instance state
  • is-a family vs can-do

The structure

Now every item extends the abstract library item class, which holds the shared parts. A book also implements both Borrowable and Reservable. An ebook implements only Borrowable. A magazine implements neither, so it has no methods it must fake. A class can extend only one class, but it can implement as many interfaces as it needs. Each capability is opted into, never forced.

Declarations
abstract class LibraryItem { .. }
interface Borrowable { .. }
interface Reservable { .. }

class Book extends LibraryItem
    implements Borrowable, Reservable
class Ebook extends LibraryItem
    implements Borrowable
class Magazine extends LibraryItem

Abstract class holds

An abstract class can hold instance fields, like the id and title. It can have constructors that validate them once for every child. It can mix finished methods, like label, with abstract ones, like shelf, that each child must fill in. Its members can be private, protected or package private. You cannot create it with new, but its constructor still runs as part of creating each child.

abstract class LibraryItem
private final String id, title;

protected LibraryItem(String id,
                      String title) {
  // validate once, for every item
}
final String label() {
  return shelf() + " / " + title;
}
abstract String shelf();

Interface holds

An interface holds abstract methods, here loan days and daily fine. Since Java eight it can also hold default methods with a body, like late fee, which every implementer gets for free and may override. It can have static methods, and since Java nine private helper methods. Its only fields are public static final constants. It has no constructor and no instance state of its own.

interface Borrowable
int loanDays();
long dailyFine();

default long lateFee(int daysLate) {
  return Math.max(0, daysLate)
      * dailyFine();
}
static Borrowable none() { .. }

// fields: only public static final

Run-through

The loan desk only knows Borrowable. It never mentions books or ebooks. When a book comes back three days late, the default late fee multiplies three days by five rupees and gives fifteen. The ebook overrides late fee to return zero, because it simply expires on the reader. Magazines cannot even be passed to the desk, so the compiler blocks the mistake that used to throw at runtime.

Default method clash

Default methods bring one catch. If Borrowable and Reservable both have a default method called rules with the same signature, a book that implements both will not compile until it overrides rules itself. Inside the override it can call either version with the interface name, dot super, dot rules. Here the book simply joins both. Note that a method inherited from a class always wins over an interface default.

Resolving the clash
interface Borrowable {
  default String rules() {..} }
interface Reservable {
  default String rules() {..} }

class Book ... {
  @Override public String rules() {
    return Borrowable.super.rules()
        + "; " + Reservable.super.rules();
  }
}

Side by side

Side by side. An abstract class can have instance state and constructors, an interface cannot. A class can implement many interfaces but extend only one class. Both can contain method bodies now, through defaults in interfaces. Interface methods are public, apart from private helpers, while an abstract class can use any access level. Neither can be created with new. Only an interface with a single abstract method can be a lambda target.

Interface vs abstract class
  • iface abstract
  • state no yes
  • constructor no yes
  • how many many one
  • method body default yes
  • access public* any
  • * private helpers allowed
  • both: cannot use new
  • lambdas: functional iface

How to choose

A simple rule. First write the contract as an interface, because callers should depend on that. If several implementations repeat the same fields and code, add an abstract base class that implements the interface and holds the shared part. If a class needs to play two roles, use interfaces for the roles, because it can only have one parent class. When in doubt, start with the interface.

A simple rule
  • 1 the contract: interface
  • (callers depend on this)
  • 2 several implementations
  • repeat the same code and
  • state? add an abstract
  • base that implements it
  • 3 one class needs two roles?
  • interfaces, not classes
  • default to the interface

Interface + skeleton

The Java collections use both together. List is the interface everyone codes against, and AbstractList is an abstract class that implements most of List on top of a few methods, so writing your own list takes very little code. The same pairing exists for Set, Map and Collection. Small capabilities, like Comparable and Runnable, are plain interfaces with no skeleton class at all.

In the JDK
  • List AbstractList
  • Set AbstractSet
  • Map AbstractMap
  • Collection AbstractCollection
  • callers use the interface;
  • implementers may extend the
  • abstract class to write less
  • Comparable, Runnable: pure
  • capabilities, no skeleton

Abuse to avoid

Some misuses to avoid. An interface that only holds constants, implemented just to avoid writing a class name, leaks those constants into every implementer. Default methods are meant to add behaviour without breaking existing implementers, not to fake state with static maps. Huge interfaces force classes to implement methods they do not need. And an abstract class with no shared code is just an interface with fewer freedoms.

Common misuses
  • • constant interfaces: an
  • interface only to hold
  • constants (use a class)
  • • defaults that fake state
  • with static maps
  • • huge interfaces with 20
  • methods (split them)
  • • abstract class with no
  • shared code (use interface)

In interviews

In an interview, do not just recite the differences. Explain the choice. Borrowable and Reservable are interfaces, because they are capabilities and a book needs both. Library item is an abstract class, because every item shares an id, a title and the validation in its constructor. The loan desk depends only on Borrowable. That answer shows you understand why, not just what.

Say it like this
  • "Borrowable and Reservable
  • are interfaces: they are
  • capabilities and a Book
  • needs both. LibraryItem is
  • abstract: every item shares
  • id, title and validation.
  • The desk depends only on
  • Borrowable."

Interview questions

What is the difference between an interface and an abstract class in Java?

An abstract class can have instance fields, constructors, methods with any access level and both abstract and concrete methods; a class can extend only one. An interface defines a contract with abstract, default, static and private methods but no instance state, and a class can implement many.

When would you choose an abstract class over an interface?

When several closely related classes share real state and code, such as common fields, constructor validation or a fixed algorithm with hooks. Even then, it is common to also define an interface for callers and have the abstract class implement it.

Why were default methods added to interfaces?

They let an interface gain new methods without breaking every existing implementation, which Java 8 needed to add methods like forEach and stream to the collection interfaces. Implementers get the default and can override it.

What happens if a class implements two interfaces with the same default method?

The class does not compile until it overrides the method. Inside the override it can call a specific version with InterfaceName.super.method(). If a superclass provides the method, the class method wins over the interface defaults.

Can an interface have fields or constructors?

An interface can declare only constants, which are implicitly public, static and final. It cannot have instance fields or constructors, because it is never instantiated on its own.

Can an abstract class have a constructor if you cannot instantiate it?

Yes. The constructor runs when a subclass is created, through the super call, and is used to initialise and validate the shared fields. It is often declared protected.

What is a functional interface?

An interface with exactly one abstract method, such as Runnable or Comparator. It can be implemented with a lambda or method reference. The @FunctionalInterface annotation makes the compiler check the rule but is optional.

How does the JDK combine interfaces and abstract classes?

Collections pair an interface with a skeletal abstract class: List with AbstractList, Map with AbstractMap. Callers depend on the interface, and implementers can extend the abstract class to get most methods built on a few primitives.