Abstract class vs interface
Junior Always asked 5 min
On this page
The question
When would you use an abstract class instead of an interface?
30-second answer
Use an interface for a capability or contract that unrelated classes can implement, several at once. Use an abstract class when closely related classes share state, constructor logic or a fixed sequence of steps with parts to fill in. Many designs use both: an interface for callers, and an abstract class implementing it for reuse.
Understand it
What each abstraction can hold
CompareAn abstract class can hold fields, constructors and any methods, but a class can extend only one.
View as text
A four-row matrix lists capabilities: instance fields, constructors, method bodies, and how many a class can use. Each row is marked for the chosen abstraction.
Abstract class: an abstract class can hold fields, constructors and any methods, but a class can extend only one. Rows read yes, yes, yes with any visibility, and one with extends.
Interface: an interface holds no instance state and no constructor, but a class can implement many, and default methods add behavior. Rows read no with constants only, no, yes as default, static or private methods, and many with implements.
A four-row matrix lists capabilities: instance fields, constructors, method bodies, and how many a class can use. Each row is marked for the chosen abstraction.
Abstract class: an abstract class can hold fields, constructors and any methods, but a class can extend only one. Rows read yes, yes, yes with any visibility, and one with extends.
Interface: an interface holds no instance state and no constructor, but a class can implement many, and default methods add behavior. Rows read no with constants only, no, yes as default, static or private methods, and many with implements.
Takeaway: An abstract class carries state and constructors but takes the only superclass slot; an interface carries no state, and a class can implement many.
Pick the right abstraction
BuildPut the abstraction that fits each case in its slot. Each piece says why it fits.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
View as text
Four design cases each need an abstraction. Put the abstraction that fits each case in its slot. Each piece says why it fits.
The answers are: Invoice and Employee must both be sortable, so use an interface, because unrelated classes share a capability. A class that already has a parent must also act as a PaymentGateway, so use an interface, because a class can adopt many. Three report types share fields and a constructor that validates them, so use an abstract class for shared state and constructor. Every importer runs the same steps and subclasses fill in one protected step, so use an abstract class as a template with a protected hook.
Interfaces for capabilities a class adds, even several; abstract classes for shared state or a fixed skeleton.
Four design cases each need an abstraction. Put the abstraction that fits each case in its slot. Each piece says why it fits.
The answers are: Invoice and Employee must both be sortable, so use an interface, because unrelated classes share a capability. A class that already has a parent must also act as a PaymentGateway, so use an interface, because a class can adopt many. Three report types share fields and a constructor that validates them, so use an abstract class for shared state and constructor. Every importer runs the same steps and subclasses fill in one protected step, so use an abstract class as a template with a protected hook.
Interfaces for capabilities a class adds, even several; abstract classes for shared state or a fixed skeleton.
Takeaway: Reach for an interface when classes add a capability, possibly several; reach for an abstract class when related classes share state or a fixed skeleton.
In code
interface PaymentGateway {
Receipt charge(Money amount);
}
abstract class AbstractGateway implements PaymentGateway {
private final RetryPolicy retry; // shared state
protected AbstractGateway(RetryPolicy retry) { this.retry = retry; }
@Override public final Receipt charge(Money amount) { // fixed steps
return retry.run(() -> doCharge(amount));
}
protected abstract Receipt doCharge(Money amount); // each provider's part
}
class CardGateway extends AbstractGateway {
CardGateway() { super(RetryPolicy.times(3)); }
@Override protected Receipt doCharge(Money amount) { return Receipt.paid(amount); }
}interface Walker { default String move() { return "walk"; } }
interface Swimmer { default String move() { return "swim"; } }
class Duck implements Walker, Swimmer {
@Override public String move() { return Walker.super.move(); } // required
}interface Discount {
double MAX = 0.5; // implicitly public static final
double rate(Order order);
default double apply(Order order, double price) { return price * (1 - cap(rate(order))); }
private static double cap(double r) { return Math.min(r, MAX); } // Java 9+
static Discount none() { return order -> 0; }
}Solve it
Choose the abstraction for three report exporters
A reporting service needs CSV, JSON and PDF exporters. All three open a file, write a header, write the rows and close
the file, counting rows as they go. The PDF exporter must extend PdfDocumentBase from a vendor library. Design the types.
- Start from the caller. Callers only need
export(report, path). That contract is an interface,ReportExporter. - Find what implementations share. Open, header, rows, close and a row counter are shared steps and state. Those belong in an abstract class that implements the interface.
- Apply the constraint. The PDF exporter already extends a vendor class, and Java has single inheritance of class. It implements the interface directly.
- Check. Callers depend only on
ReportExporter, so all three are interchangeable. The abstract class is an optional helper, not something callers know about.
interface ReportExporter { int export(Report report, Path path) throws IOException; }
abstract class LineExporter implements ReportExporter {
@Override public final int export(Report report, Path path) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(path)) {
out.write(header(report));
int rows = 0;
for (Row row : report.rows()) { out.write(line(row)); rows++; }
return rows;
}
}
protected abstract String header(Report report);
protected abstract String line(Row row);
}
class CsvExporter extends LineExporter {
protected String header(Report r) { return String.join(",", r.columns()) + "\n"; }
protected String line(Row row) { return String.join(",", row.values()) + "\n"; }
}
class PdfExporter extends PdfDocumentBase implements ReportExporter { // vendor base class
@Override public int export(Report report, Path path) { return render(report, path); }
}How to answer
- Interface: a contract with no instance state; a class can implement many.
- Abstract class: shared fields, constructors and protected helpers; a class extends only one.
- Default methods let an interface grow without breaking its implementers.
- Callers depend on the interface; the abstract class is an implementation aid.
Common mistakes
- Saying interfaces cannot have method bodies; Java 8 added default and static methods, and Java 9 private ones.
- Choosing an abstract class to share one helper method, which uses up the class's only superclass.
Follow-up questions
Why were default methods added to interfaces in Java 8?
To grow interfaces without breaking every class that implements them. Java 8 added forEach to Iterable and stream to Collection; as default methods with a body, existing implementations inherited them instead of failing to compile.
- Adding an abstract method to an interface breaks every implementer.
- A default method supplies a body that implementers may override.
- Default methods carry behavior, never instance state.
What happens if a class implements two interfaces that declare the same default method?
The class does not compile until it overrides the method. Inside the override it can call one parent's version explicitly with Walker.super.move().
- Two inherited defaults with one signature are a compile error.
- The class must override the method and may delegate with Interface.super.method().
interface Walker { default String move() { return "walk"; } }
interface Swimmer { default String move() { return "swim"; } }
class Duck implements Walker, Swimmer {
@Override public String move() { return Walker.super.move(); }
} What does multiple inheritance of type mean in Java?
A class can implement many interfaces, so its objects can be used as each of those types: a Duck can be passed wherever a Walker or a Swimmer is expected. It still extends only one class, so it inherits fields and constructors from a single parent.
- Many types, through interfaces.
- One superclass, so state comes from one parent.
- Default methods add inheritance of behavior, with explicit conflict rules.
See it in the infographic: What each abstraction can hold See it in the infographic: Pick the right abstraction
Why does an abstract class have a constructor if you cannot instantiate it?
Subclass constructors call it through super(...). It initializes and validates the fields the abstract class declares, so every subclass object starts in a valid state.
newon an abstract class does not compile.- Every subclass constructor runs its parent's constructor first.
- It is the one place to validate the shared fields.
How would you design payment providers that share retry logic but stay pluggable?
Define a PaymentGateway interface that callers depend on. Add an AbstractGateway that implements it, holds the shared retry and logging code and leaves one protected method, doCharge(), to each provider. Providers extend the abstract class; one that cannot extend it can still implement the interface directly.
- Callers see only the interface.
- The abstract class shares the code as a template.
- The interface stays open to providers that already have another parent.
See it in the infographic: Pick the right abstraction See it in the infographic: What each abstraction can hold
Why can interfaces have private methods?
Java 9 added them so default methods can share helper code without making that helper part of the interface's public contract.
Can an abstract class have no abstract methods?
Yes. Declaring it abstract only stops anyone instantiating it, which suits a base class meant to be extended, such as a template whose hooks have empty bodies.
Can an interface declare fields?
Only constants: every interface field is implicitly public, static and final. There is no per-object state, and that is the main thing an abstract class adds.
Check yourself
Show answers
- It is public, static and final: Correct. Interface fields are implicitly constants.
- Each implementing object gets its own copy: Incorrect. Interfaces hold no instance state.
- It must be private: Incorrect. Interface fields are always public; private fields are not allowed.
Show answers
- implements Exportable, Printable: Correct. A class can implement any number of interfaces.
- A second extends clause: Incorrect. A class extends exactly one class.
- Nothing more: Incorrect. A class that extends another can still implement interfaces.
Show answers
- An interface: Correct. Unrelated classes can each add an interface.
- An abstract class: Incorrect. Both classes already have a parent, and a class extends only one.
- A concrete class: Incorrect. Extending it would also need the only superclass slot.