← Java roadmap

Topic 8 of 30 · Intermediate

Abstract Classes & Interfaces

Contracts, default methods and sealed types.

Concept

An abstract class can have state, constructors and both abstract and concrete methods. A class can extend only one.

An interface defines a contract. Since Java 8 it can have default and static methods; a class can implement many interfaces.

Sealed classes/interfaces (Java 17) restrict which classes may extend them, useful with pattern-matching switch.

Cheat sheet

FeatureAbstract classInterface
MultipleNo (extend one)Yes (implement many)
StateAny fieldsOnly constants
ConstructorYesNo
Use whenShared base codeCapability / contract

Code (Java 21)

interface Payable {
    double amount();
    default String receipt() { return "Paid " + amount(); }
}

sealed interface Result permits Ok, Err {}
record Ok(String data) implements Result {}
record Err(String msg) implements Result {}

static String show(Result r) {
    return switch (r) {
        case Ok ok -> "OK: " + ok.data();
        case Err e -> "Error: " + e.msg();
    };
}

Remember

  • Interface fields are public static final.
  • Functional interface = exactly one abstract method.
  • Sealed + switch = exhaustive checks.

Interview questions

When to choose an abstract class over an interface?

When related classes share state or implementation. Use interfaces for capabilities that unrelated classes can have.

What is a functional interface?

An interface with exactly one abstract method (e.g. Runnable, Comparator), usable as a lambda target.

Practise Java with the AI mentor

Lesson test

Take an 8-question test on “Abstract Classes & Interfaces” — concepts, output prediction, bug spotting and interview questions.

Can't find a Java topic you need for exams or placements? Request it and we'll add it.