An interface is a contract: a list of methods a class promises to provide, with no state and (usually) no code. An abstract class is a partial class: it holds real fields, constructors and working methods, and leaves a few abstract methods for its subclasses to fill in. Both let callers depend on an abstract type instead of a concrete class, which is the first principle of the Gang of Four book: program to an interface, not an implementation. Knowing which tool to reach for, and what each one costs when the design changes, is one of the most common low-level design questions in interviews.
Think of it like
A job description and a franchise
A job description (an interface) lists what the role must do: "can drive a forklift, can sign for deliveries". Anyone who can do those things can fill the role, whatever their background, and one person can hold two roles at once. A franchise (an abstract class) hands you a working restaurant: the kitchen layout, the supply chain and the opening hours are already decided, and you only fill in the parts left blank, such as the local menu. You get a lot for free, but you can belong to only one franchise, and when head office changes the playbook, every branch inherits the change.
What an interface is
An interface names a set of operations and their signatures, and nothing else. It has no fields and no constructor, so it cannot be instantiated. A class implements it by providing every method, and from then on an object of that class can be used anywhere the interface type is expected. The interface says what callers may rely on; each implementer decides how.
interface Exporter {
export(items: string[]): string;
}
interface Notifier {
send(msg: string): string;
}
class SlackBot implements Exporter, Notifier {
constructor(private channel: string) {}
export(items: string[]): string {
return this.channel + ": " + items.join(", ");
}
send(msg: string): string {
return this.channel + ": " + msg;
}
}
// The caller depends on the contract only.
function publish(outs: Exporter[], items: string[]): void {
for (const out of outs) {
console.log(out.export(items)); // which class? does not matter
}
}- Unrelated classes can implement it.
SlackBotshares no code and no ancestor with a Markdown exporter, yet both areExporters. Nothing ties implementers together except the promise. - A class can implement many. Java, TypeScript and C# allow one superclass but any number of interfaces, so a class can play several roles. Here the same object is an
Exporterto one caller and aNotifierto another. - Callers see only the contract. A variable typed
Notifierexposessend()and nothing else, even though the object behind it can also export.
Program to an interface means typing your fields, parameters and return values with the interface rather than a concrete class, as publish() does. Code written against Exporter compiles without importing any exporter class, works with exporters written next year, and can be tested with a fake one. This is the same abstraction pillar from The Four Pillars of OOP, made explicit.
What an abstract class is
An abstract class is a class that cannot be instantiated on its own because some of its methods are declared but not written: they are abstract. Everything else is an ordinary class: it can have private fields, constructors that set them up, and concrete methods with real code. A subclass inherits all of that and only has to supply the missing methods.
abstract class TextExporter implements Exporter {
private exported = 0; // state
constructor(private format: string) {} // a real constructor
export(items: string[]): string { // shared code
const lines = items.map((item) => this.line(item));
this.exported += items.length;
return lines.join("\n");
}
protected abstract line(item: string): string; // the gap
}
class MarkdownExporter extends TextExporter {
constructor() {
super("markdown");
}
protected line(item: string): string {
return "- " + item;
}
}- Abstract method
- A method with a signature and no body. Every concrete subclass must implement it, or it is abstract too.
- Concrete method
- A method with a body, inherited as is (or overridden) by subclasses.
export()above is one. - Template method
- A concrete method that fixes the order of the steps and calls abstract methods for the steps that vary. The base class calls down into the subclass.
- Hook
- The method a template method calls for a varying step, here
line(). Some hooks are abstract (must be written); others have a default body that subclasses may override.
Watch it run
The visualizer at the top of the page runs exactly this design. Exporter and Notifier are interfaces; TextExporter is the abstract base with a template method export(); MarkdownExporter and HtmlExporter write only line(); SlackBot implements both interfaces directly. Press Play, or step with the arrow keys, and read the caption under the stage.
- Class diagram: dashed lines with hollow triangles are implements; solid ones are inherits. When a method is called, the type that declares it turns violet and the class whose code runs turns amber. That split is the whole lesson: violet is the contract, amber is the implementation.
- Objects:
mdandhtmleach show anexportedfield although their classes never declare one: it comes fromTextExporter.slackshows only itschannel. - Sequence: a call to
line()is a loop onmd's own lifeline. The object calls itself, and the code moves from the base class down to the subclass.
- 1
Create three exporters
mdandhtmlstart withexported = 0, set up by the abstract class.slackgetschannel = "#ops"from its own constructor. - 2
Call through the contract
The client loops over
Exporter[]and callsmd.export(["tea", "jam"]).Exporter.exportturns violet andTextExporter.exportamber: the inherited template method runs. - 3
The base class calls down
export()callsthis.line("tea").TextExporter.lineis violet (declared, abstract) andMarkdownExporter.lineamber; it returns"- tea", then"- jam". - 4
Shared state changes
Back in the base class,
md.exportedgoes from 0 to 2, andexport()returns"- tea\n- jam". The subclass wrote one line of code; the loop, the counter and the join are shared. - 5
Same template, another hook
html.export(...)runs the sameTextExporter.export, but the hook now resolves toHtmlExporter.line, producing<li>tea</li>and<li>jam</li>. - 6
Same contract, no shared code
slack.export(...)lightsExporter.exportagain, but nowSlackBot.exportruns its own code and returns"#ops: tea, jam". Nothing was inherited. - 7
One object, second role
The client stores
slackin aNotifiervariable and callssend("list sent"). This timeNotifier.sendis violet and theNotifierimplements edge lights up. - 8
Grow the contract
Press Add preview(). The change request adds one method,
preview(items), toExporter, and the run ends withmd.preview(...)(inherited, returns"- tea") andslack.preview(...)(its own, returns"#ops: tea"). The table below counts who had to change.
| Change request: add preview() to Exporter | Lines changed | Why |
|---|---|---|
Exporter (interface) | +1 | The contract gains a method |
TextExporter (abstract base) | +3 | It implements Exporter, so it must write preview(): once, reusing the line() hook |
SlackBot | +4 | It implements Exporter directly, so it must write its own |
MarkdownExporter, HtmlExporter | 0 | They inherit preview() from the base class |
This is the trade-off in miniature. Growing an interface breaks every class that implements it directly, because each one made the promise separately. An abstract base absorbs the change for all of its subclasses, because they inherit the new concrete method. In a library with many implementers outside your control, that difference decides whether a new method is a minor release or a breaking one.
Interface vs abstract class
| Interface | Abstract class | |
|---|---|---|
| Purpose | A contract: what callers may rely on | A partial implementation: shared code plus gaps |
| Instance fields (state) | No (Java allows only static final constants) | Yes, any fields |
| Constructors | No | Yes, run through super(...) by subclasses |
| Method bodies | None, or default methods in Java 8+ and C# 8+ (which cannot use instance fields) | Concrete and abstract methods side by side |
| How many per class | Many: a class can implement several | One superclass in Java, TypeScript and C# |
| Who can implement it | Any class, even from an unrelated hierarchy | Only subclasses, which give up their one extends |
| Adding a method later | Every direct implementer breaks (unless a default body is given) | Add a concrete method: subclasses get it for free |
| Changing shared code | Nothing shared to change | One edit reaches every subclass, for better or worse |
| Typical role | Capabilities and roles: Comparable, Runnable, Exporter | A family's skeleton: AbstractList, HttpServlet |
Reach for an interface when
- Unrelated classes must be usable in the same place
- A class needs to play more than one role
- You want callers decoupled from every implementation, including fakes in tests
- There is no meaningful code to share
Reach for an abstract class when
- Several closely related classes share real state and code
- There is a fixed algorithm with a few varying steps (a template method)
- You want to add methods later without breaking subclasses
- Subclasses are a genuine is-a family
How each language does it
Java
Java has both keywords. Since Java 8 an interface may contain default methods (with a body, inherited by implementers) and static methods; Java 9 added private interface methods for sharing code between defaults. Interfaces still have no instance fields: any field is implicitly public static final. Default methods were added so that interfaces like Collection and Iterable could grow (stream(), forEach()) without breaking every existing implementation. If a class inherits two default methods with the same signature from unrelated interfaces, the compiler refuses until the class overrides the method (it can still call one with Left.super.method()).
interface Exporter {
String export(List<String> items);
// Added later: existing implementers inherit this body.
default String preview(List<String> items) {
return items.isEmpty() ? "" : export(items.subList(0, 1));
}
static Exporter plain() {
return items -> String.join(", ", items);
}
}TypeScript
TypeScript interfaces exist only at compile time: they are erased from the JavaScript output, so x instanceof Exporter is an error. Typing is structural: any object with the right methods is an Exporter, whether or not its class says implements Exporter. The implements clause is only a check that the class matches: a plain object literal with an export(items) method can be passed to publish() as it is. (Go takes the same idea further: it has only interfaces, and any type with the right methods satisfies one implicitly.) Abstract classes, by contrast, compile to real JavaScript classes that exist at runtime; only the abstract keyword and abstract members are erased, so the rule "cannot be instantiated" is enforced by the compiler, not by JavaScript.
Python
Python offers two tools. abc.ABC with @abstractmethod builds an abstract base class: instantiating a class that still has abstract methods raises TypeError, and the ABC can hold __init__, state and concrete methods. typing.Protocol (Python 3.8, PEP 544) describes a structural interface: classes match it by shape without inheriting from it, and static type checkers such as mypy and pyright verify the match. At runtime a protocol does nothing unless it is marked @runtime_checkable, and even then isinstance only checks that the methods exist, not their signatures.
from abc import ABC, abstractmethod
from typing import Protocol
class Exporter(Protocol):
def export(self, items: list[str]) -> str: ...
class TextExporter(ABC):
def export(self, items: list[str]) -> str:
return "\n".join(self._line(item) for item in items)
@abstractmethod
def _line(self, item: str) -> str: ...
TextExporter() # TypeError: can't instantiate abstract classC++
C++ has no interface keyword. A class becomes abstract when it declares at least one pure virtual function (virtual ... = 0), and an abstract class cannot be instantiated. An "interface" is simply an abstract class with only pure virtual functions and a public virtual destructor, so that deleting an object through an interface pointer runs the right destructor. Because C++ has multiple inheritance, a class can derive from several such interfaces.
class Notifier {
public:
virtual ~Notifier() = default;
virtual std::string send(const std::string& msg) = 0;
};
class SlackBot : public Exporter, public Notifier {
// must override every pure virtual function of both bases
};Choosing between them
- 1Start with an interface for anything callers depend on. It is the smallest promise and the easiest to fake in tests.
- 2Is there real code that every implementation would otherwise copy? If not, stop: the interface is enough.
- 3If yes, add an abstract class that implements the interface and holds that code. Callers still depend on the interface; implementers can extend the base for convenience or implement the interface from scratch.
- 4Is the shared code a fixed sequence with varying steps? Make it a template method in the base with abstract hooks, as
TextExporter.export()does. - 5Would subclasses need different combinations of behavior? Prefer composing small objects behind interfaces to growing the hierarchy, as shown in Composition vs Inheritance and Strategy.
A preview of interface segregation
Notice that the scenario has two small interfaces, not one big one. If Exporter also declared send(), MarkdownExporter would have to implement a messaging method it has no use for, probably by throwing an error. The interface segregation principle, the I in SOLID Principles, says clients should not be forced to depend on methods they do not use: split fat interfaces into role-sized ones.
interface Channel { // too many roles in one contract
export(items: string[]): string;
send(msg: string): string;
schedule(cron: string): void;
}
class MarkdownExporter implements Channel {
export(items: string[]) { return items.join("\n"); }
send(): string { throw new Error("not supported"); } // smell
schedule(): void { throw new Error("not supported"); } // smell
}Common mistakes
- An abstract class used as an interface. A base class with only abstract methods and no state takes the subclass's single
extendsslot for nothing. Make it an interface. - An interface for every class.
IUserServicewith one implementation and no test double adds a file and a jump without decoupling anything. Extract the interface when a second implementation, or a fake, actually appears. - Leaking implementation through the contract. An interface method like
getSqlConnection()ties every implementer to one technology. Name what the caller needs (findUser(id)), not how one implementation does it. - Calling an abstract hook from the base constructor. The subclass is not fully initialized yet: in Java and TypeScript the override runs before the subclass's own fields are set, and in C++ the call does not reach the subclass at all (a pure virtual call there typically aborts the program).
- Growing a published interface carelessly. Every new abstract method breaks every implementer you do not control. Add a default body, a new extended interface, or a method on a skeletal base class instead.
Implementation
The scenario as a complete program with the change request applied: two interfaces (Exporter with export and preview, Notifier with send), an abstract TextExporter that holds a counter, a constructor and a template method calling the abstract line hook, two subclasses that only write line, and a SlackBot that implements both interfaces with its own code. Python expresses the contracts as typing.Protocol classes that SlackBot matches by shape. In C++ export is a reserved word, so the method is called exportItems there.
from abc import ABC, abstractmethod
from typing import Protocol
# The contracts: structural, so implementers need not inherit them.
class Exporter(Protocol):
def export(self, items: list[str]) -> str: ...
def preview(self, items: list[str]) -> str: ...
class Notifier(Protocol):
def send(self, msg: str) -> str: ...
# The shared implementation: state, __init__ and a template method.
class TextExporter(ABC):
def __init__(self, fmt: str) -> None:
self._format = fmt
self._exported = 0
# Template method: the fixed steps, written once for every subclass.
def export(self, items: list[str]) -> str:
lines = [self._line(item) for item in items]
self._exported += len(items)
return "\n".join(lines)
def preview(self, items: list[str]) -> str:
return self._line(items[0]) if items else ""
def summary(self) -> str:
return f"{self._format}: {self._exported} items exported"
# The hook: the one step only a subclass knows how to do.
@abstractmethod
def _line(self, item: str) -> str: ...
class MarkdownExporter(TextExporter):
def __init__(self) -> None:
super().__init__("markdown")
def _line(self, item: str) -> str:
return f"- {item}"
class HtmlExporter(TextExporter):
def __init__(self) -> None:
super().__init__("html")
def _line(self, item: str) -> str:
return f"<li>{item}</li>"
# No base class at all: it matches both protocols by shape.
class SlackBot:
def __init__(self, channel: str) -> None:
self._channel = channel
def export(self, items: list[str]) -> str:
return f"{self._channel}: " + ", ".join(items)
def preview(self, items: list[str]) -> str:
first = items[0] if items else ""
return f"{self._channel}: {first}"
def send(self, msg: str) -> str:
return f"{self._channel}: {msg}"
# Client code depends only on the protocol.
def publish(outs: list[Exporter], items: list[str]) -> None:
for out in outs:
print(out.export(items))
md = MarkdownExporter()
html = HtmlExporter()
slack = SlackBot("#ops")
items = ["tea", "jam"]
publish([md, html, slack], items)
notifier: Notifier = slack # same object, another role
print(notifier.send("list sent"))
print(md.preview(items))
print(slack.preview(items))
print(md.summary())
try:
TextExporter("csv")
except TypeError:
print("TextExporter is abstract")
# Output:
# - tea
# - jam
# <li>tea</li>
# <li>jam</li>
# #ops: tea, jam
# #ops: list sent
# - tea
# #ops: tea
# markdown: 2 items exported
# TextExporter is abstractKey takeaways
- An interface is a contract (what), with no state and no constructor; an abstract class is a partial implementation (how), with fields, constructors, concrete methods and abstract gaps.
- Program to an interface: type fields and parameters with the abstract type, so callers work with any implementation, present or future, including test fakes.
- A class can implement many interfaces but extend only one class (in Java, TypeScript and C#), so interfaces model roles that unrelated classes can share;
SlackBotis both anExporterand aNotifier. - An abstract class shines with a template method: shared code in the base calls an abstract hook, and each subclass writes only the step that varies (
line()in the visualizer). - They change differently: adding
preview()toExporteredited every direct implementer (TextExporter,SlackBot), while the abstract base gave it to both subclasses for free. - They combine well: an interface for callers plus a skeletal abstract class for implementers, like Java's
ListandAbstractList.
Common pitfalls
- Using an abstract class with no state and no concrete methods: it is an interface that wastes the subclass's only
extends. - Creating an interface for every class "just in case": indirection with no second implementation and no test double to justify it.
- Fat interfaces that force implementers to throw "not supported" for methods they cannot honor; split them by role (interface segregation).
- Calling an abstract or overridable method from a base-class constructor, before the subclass is initialized.
- Adding abstract methods to a published interface, which breaks every implementer you do not control; use a default method, a new interface or a skeletal base class.
Interview tips
- Answer "interface vs abstract class" on two levels: the mechanics (state, constructors, multiple inheritance, default methods) and the design intent (a role versus a shared skeleton).
- Mention how each one evolves: a new interface method breaks implementers unless it has a default, while a new concrete method on an abstract base reaches all subclasses.
- Know the language twists: Java 8 default methods, TypeScript interfaces erased and structural, Python ABCs vs
typing.Protocol, C++ pure virtual functions with no interface keyword. - Show you can combine them: an interface for callers, a skeletal abstract class for implementers, and composition when behavior varies in more than one direction.
Real-world applications
- Plugin and driver APIs: JDBC's
ConnectionandDriverinterfaces let any database vendor plug into the same Java code. - Capability interfaces in standard libraries: Java's
Comparable,RunnableandAutoCloseable, which unrelated classes implement to join sorting, threads or try-with-resources. - Skeletal base classes:
AbstractListandAbstractMapin Java, and Python'scollections.abcclasses such asMapping, which supply many methods once you write a few. - Framework hooks through template methods:
HttpServlet.service()dispatches to thedoGet()anddoPost()you override; a Node.jsReadablestream calls your_read(). - Testing: code written against an interface accepts an in-memory fake (a fake payment gateway, a fake clock) without a mocking library.
Test yourself
In the visualizer, the client calls md.export(["tea", "jam"]) on a MarkdownExporter. Whose code runs for export()?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.