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
| Feature | Abstract class | Interface |
|---|---|---|
| Multiple | No (extend one) | Yes (implement many) |
| State | Any fields | Only constants |
| Constructor | Yes | No |
| Use when | Shared base code | Capability / 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.
Lesson test
Take an 8-question test on “Abstract Classes & Interfaces” — concepts, output prediction, bug spotting and interview questions.