Interfaces vs Abstract Classes
Introduction
You are designing a notification system. Email, SMS and push messages must each be able to send() and to check a recipient, and they also share some work: every channel logs what it does and retries when sending fails.
Should the common part be an interface, which only says what a channel must do? Or an abstract class, which can also hold the shared code? Abstraction — Hiding Complexity showed why a caller should see only what an object does. Interfaces and abstract classes are the two tools object-oriented languages give you for that, and knowing which one fits keeps a design easy to extend.
What Is an Interface?
An interface is a contract. It lists the methods a class must offer, with their names, parameters and return types, and it leaves the work to the classes that take it on.
Think of a job description. A restaurant posts "must be able to cook, plate food and manage stock". The posting does not say how to cook; any chef who can do those things can take the job, whatever their style.
An interface has these traits:
- It declares method signatures, and each class that implements it writes those methods.
- It holds no state of its own. In Java its fields are constants: the Java tutorial says "all fields are automatically public, static, and final".
- A class can implement as many interfaces as it needs.
- You cannot make an object of an interface itself: in the Java tutorial's words, "Interfaces cannot be instantiated"; classes implement them, and other interfaces can extend them.
An interface is not always free of code. In Java, "Method bodies exist only for default methods and static methods", and the Java Language Specification also allows private methods that its default methods use. A test showed a default greet() calling a private helper inside an interface, and it printed Hello, ANA. Default methods exist so that an interface can grow without breaking the classes that already implement it: "Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces."
Interfaces let classes that have nothing else in common share one capability. An EmailChannel and a PrinterQueue share no data and no history, yet both could be Sendable, and code that only needs to send can take either.
What Is an Abstract Class?
An abstract class is a partial blueprint. It can declare methods that its subclasses must write, and it can also give them shared code and state.
Think of a restaurant chain's recipe template. Head office fixes the sauce, the cooking temperature and the plating; each branch picks its own toppings. The template holds the common part, and the branches fill in the rest.
An abstract class has these traits:
- It can have abstract methods, with no body, that each subclass must write.
- It can have concrete methods, with a body, that every subclass inherits.
- It can hold instance state (fields) and have constructors.
- A class can extend only one class, abstract or not.
- You cannot make an object of an abstract class. javac refused
new NotificationChannel("TEST")withNotificationChannel is abstract; cannot be instantiated, and Python refused it withTypeError: Can't instantiate abstract class NotificationChannel without an implementation for abstract methods 'send', 'validate_recipient'.
Abstract classes suit related classes that share both a contract and code. If every notification channel logs and retries, writing that logic once in the parent keeps the copies from drifting apart, which is the idea behind DRY — Don't Repeat Yourself.
Key Differences, Side by Side
Here is the comparison in one place, with Java's rules where the languages differ:
| Feature | Interface | Abstract class |
|---|---|---|
| Purpose | A contract: what to do | A partial blueprint: what, and some of how |
| Method bodies | Only default, static and private methods (Java) | Any mix of abstract and concrete methods |
| State | Constants only | Instance fields |
| Constructor | None | Yes, called by subclasses |
| How many a class takes | Any number | One |
| Access | Public, or private for helper methods | Public, protected, package or private |
| When to use | Unrelated classes share a capability | Closely related classes share code |
| In a UML diagram | The keyword «interface»; a dashed arrow with a hollow head | The name in italics; a solid arrow with a hollow head |
The Java tutorial sums up the difference in two sentences: "With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces." The Java Language Specification now allows private methods as well: "A method in the body of an interface declaration may be declared public or private".
The question to ask is whether your classes share behaviour or only a contract:
- If they share code and state, use an abstract class.
- If they share only the method names and each does the work its own way, use an interface.
- If a class must play several roles, use interfaces for the roles, since it can take as many as it needs.
The picture shows the listing below in the language of class diagrams, with what each kind can hold beside it.

Code Example
Here is a notification system that uses both. Sendable is the interface: every channel must be able to send and to validate_recipient. NotificationChannel is the abstract class: it implements Sendable, holds each channel's name and a count, and writes the shared log and send_with_retry once. In this example the SMS gateway is busy on the first try, so the retry has something to do. Go has no abstract classes, and its listing says in a comment how it shares the code instead:
from abc import ABC, abstractmethod
from dataclasses import dataclass
# The interface: what anything that sends a message must offer. Python has no interface
# keyword, so an ABC with only abstract methods and no state plays the part
class Sendable(ABC):
@abstractmethod
def send(self, recipient: str, message: str) -> bool: ...
@abstractmethod
def validate_recipient(self, recipient: str) -> bool: ...
# The abstract class: the code every channel shares (its name, a count, the log and the
# retries). It leaves send() and validate_recipient() to each channel
class NotificationChannel(Sendable):
def __init__(self, channel_name: str, max_retries: int = 3) -> None:
self._channel_name = channel_name
self._max_retries = max_retries
self._sent_count = 0
def log(self, text: str) -> None:
print(f" [{self._channel_name}] {text}")
def send_with_retry(self, recipient: str, message: str) -> bool:
if not self.validate_recipient(recipient):
self.log(f"Invalid recipient: {recipient}")
return False
for attempt in range(1, self._max_retries + 1):
self.log(f"Attempt {attempt}/{self._max_retries}")
if self.send(recipient, message):
self._sent_count += 1
self.log(f"Sent (total: {self._sent_count})")
return True
self.log(f"Attempt {attempt} failed")
self.log("All retries used up")
return False
class EmailChannel(NotificationChannel):
def __init__(self) -> None:
super().__init__("EMAIL")
def send(self, recipient: str, message: str) -> bool:
self.log(f"Email to {recipient}: {message}")
return True
def validate_recipient(self, recipient: str) -> bool:
return "@" in recipient and "." in recipient
# In this example the SMS gateway is busy on the first try, so the shared retry is used
class SMSChannel(NotificationChannel):
def __init__(self) -> None:
super().__init__("SMS")
self._busy_tries = 1
def send(self, recipient: str, message: str) -> bool:
if self._busy_tries > 0:
self._busy_tries -= 1
self.log("Gateway busy")
return False
self.log(f"SMS to {recipient}: {message[:160]}")
return True
def validate_recipient(self, recipient: str) -> bool:
return recipient.startswith("+") and len(recipient) >= 10
class PushChannel(NotificationChannel):
def __init__(self) -> None:
super().__init__("PUSH")
def send(self, recipient: str, message: str) -> bool:
self.log(f"Push to device {recipient}: {message}")
return True
def validate_recipient(self, recipient: str) -> bool:
return len(recipient) == 36 # a device token written as a UUID
@dataclass(frozen=True)
class Delivery:
channel: NotificationChannel
recipient: str
# Every channel is used the same way, through the abstract class
def notify_user(deliveries: list[Delivery], message: str) -> None:
for delivery in deliveries:
delivery.channel.send_with_retry(delivery.recipient, message)
notify_user([
Delivery(EmailChannel(), "alice@example.com"),
Delivery(SMSChannel(), "+1234567890"),
Delivery(PushChannel(), "a1b2c3d4-e5f6-7890-abcd-ef1234567890"),
Delivery(SMSChannel(), "12345"),
], "Your order #1234 has shipped!")import java.util.List;
// The interface: what anything that sends a message must offer
interface Sendable {
boolean send(String recipient, String message);
boolean validateRecipient(String recipient);
}
// The abstract class: the code every channel shares (its name, a count, the log and the
// retries). It leaves send() and validateRecipient() to each channel
abstract class NotificationChannel implements Sendable {
private final String channelName;
private final int maxRetries;
private int sentCount = 0;
protected NotificationChannel(String channelName, int maxRetries) {
this.channelName = channelName;
this.maxRetries = maxRetries;
}
protected NotificationChannel(String channelName) {
this(channelName, 3);
}
protected void log(String text) {
System.out.println(" [" + channelName + "] " + text);
}
public boolean sendWithRetry(String recipient, String message) {
if (!validateRecipient(recipient)) {
log("Invalid recipient: " + recipient);
return false;
}
for (int attempt = 1; attempt <= maxRetries; attempt++) {
log("Attempt " + attempt + "/" + maxRetries);
if (send(recipient, message)) {
sentCount++;
log("Sent (total: " + sentCount + ")");
return true;
}
log("Attempt " + attempt + " failed");
}
log("All retries used up");
return false;
}
}
class EmailChannel extends NotificationChannel {
EmailChannel() {
super("EMAIL");
}
@Override
public boolean send(String recipient, String message) {
log("Email to " + recipient + ": " + message);
return true;
}
@Override
public boolean validateRecipient(String recipient) {
return recipient.contains("@") && recipient.contains(".");
}
}
// In this example the SMS gateway is busy on the first try, so the shared retry is used
class SMSChannel extends NotificationChannel {
private int busyTries = 1;
SMSChannel() {
super("SMS");
}
@Override
public boolean send(String recipient, String message) {
if (busyTries > 0) {
busyTries--;
log("Gateway busy");
return false;
}
int length = Math.min(160, message.length());
log("SMS to " + recipient + ": " + message.substring(0, length));
return true;
}
@Override
public boolean validateRecipient(String recipient) {
return recipient.startsWith("+") && recipient.length() >= 10;
}
}
class PushChannel extends NotificationChannel {
PushChannel() {
super("PUSH");
}
@Override
public boolean send(String recipient, String message) {
log("Push to device " + recipient + ": " + message);
return true;
}
@Override
public boolean validateRecipient(String recipient) {
return recipient.length() == 36; // a device token written as a UUID
}
}
record Delivery(NotificationChannel channel, String recipient) {}
public class NotifyDemo {
// Every channel is used the same way, through the abstract class
static void notifyUser(List<Delivery> deliveries, String message) {
for (Delivery delivery : deliveries) {
delivery.channel().sendWithRetry(delivery.recipient(), message);
}
}
public static void main(String[] args) {
List<Delivery> deliveries = List.of(
new Delivery(new EmailChannel(), "alice@example.com"),
new Delivery(new SMSChannel(), "+1234567890"),
new Delivery(new PushChannel(), "a1b2c3d4-e5f6-7890-abcd-ef1234567890"),
new Delivery(new SMSChannel(), "12345"));
notifyUser(deliveries, "Your order #1234 has shipped!");
}
}#include <algorithm>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
// The interface. C++ has no interface keyword: a class with only pure virtual
// functions and no data plays the part
class Sendable {
public:
virtual ~Sendable() = default;
virtual bool send(const std::string& recipient, const std::string& message) = 0;
virtual bool validateRecipient(const std::string& recipient) const = 0;
};
// The abstract class: the code every channel shares (its name, a count, the log and the
// retries). It leaves send() and validateRecipient() to each channel
class NotificationChannel : public Sendable {
public:
explicit NotificationChannel(std::string channelName, int maxRetries = 3)
: channelName_(std::move(channelName)), maxRetries_(maxRetries) {}
bool sendWithRetry(const std::string& recipient, const std::string& message) {
if (!validateRecipient(recipient)) {
log("Invalid recipient: " + recipient);
return false;
}
for (int attempt = 1; attempt <= maxRetries_; attempt++) {
log("Attempt " + std::to_string(attempt) + "/" +
std::to_string(maxRetries_));
if (send(recipient, message)) {
sentCount_++;
log("Sent (total: " + std::to_string(sentCount_) + ")");
return true;
}
log("Attempt " + std::to_string(attempt) + " failed");
}
log("All retries used up");
return false;
}
protected:
void log(const std::string& text) const {
std::printf(" [%s] %s\n", channelName_.c_str(), text.c_str());
}
private:
std::string channelName_;
int maxRetries_;
int sentCount_ = 0;
};
class EmailChannel : public NotificationChannel {
public:
EmailChannel() : NotificationChannel("EMAIL") {}
bool send(const std::string& recipient, const std::string& message) override {
log("Email to " + recipient + ": " + message);
return true;
}
bool validateRecipient(const std::string& recipient) const override {
return recipient.find('@') != std::string::npos &&
recipient.find('.') != std::string::npos;
}
};
// In this example the SMS gateway is busy on the first try, so the shared retry is used
class SMSChannel : public NotificationChannel {
public:
SMSChannel() : NotificationChannel("SMS") {}
bool send(const std::string& recipient, const std::string& message) override {
if (busyTries_ > 0) {
busyTries_--;
log("Gateway busy");
return false;
}
const size_t length = std::min<size_t>(160, message.size());
log("SMS to " + recipient + ": " + message.substr(0, length));
return true;
}
bool validateRecipient(const std::string& recipient) const override {
return !recipient.empty() && recipient[0] == '+' && recipient.size() >= 10;
}
private:
int busyTries_ = 1;
};
class PushChannel : public NotificationChannel {
public:
PushChannel() : NotificationChannel("PUSH") {}
bool send(const std::string& recipient, const std::string& message) override {
log("Push to device " + recipient + ": " + message);
return true;
}
bool validateRecipient(const std::string& recipient) const override {
return recipient.size() == 36; // a device token written as a UUID
}
};
struct Delivery {
std::unique_ptr<NotificationChannel> channel;
std::string recipient;
};
// Every channel is used the same way, through the abstract class
void notifyUser(std::vector<Delivery>& deliveries, const std::string& message) {
for (Delivery& delivery : deliveries) {
delivery.channel->sendWithRetry(delivery.recipient, message);
}
}
int main() {
std::vector<Delivery> deliveries;
deliveries.push_back({std::make_unique<EmailChannel>(), "alice@example.com"});
deliveries.push_back({std::make_unique<SMSChannel>(), "+1234567890"});
deliveries.push_back(
{std::make_unique<PushChannel>(), "a1b2c3d4-e5f6-7890-abcd-ef1234567890"});
deliveries.push_back({std::make_unique<SMSChannel>(), "12345"});
notifyUser(deliveries, "Your order #1234 has shipped!");
return 0;
}// The interface: what anything that sends a message must offer
interface Sendable {
send(recipient: string, message: string): boolean;
validateRecipient(recipient: string): boolean;
}
// The abstract class: the code every channel shares (its name, a count, the log and the
// retries). It leaves send() and validateRecipient() to each channel
abstract class NotificationChannel implements Sendable {
private sentCount = 0;
protected constructor(
private readonly channelName: string,
private readonly maxRetries = 3,
) {}
abstract send(recipient: string, message: string): boolean;
abstract validateRecipient(recipient: string): boolean;
protected log(text: string): void {
console.log(` [${this.channelName}] ${text}`);
}
sendWithRetry(recipient: string, message: string): boolean {
if (!this.validateRecipient(recipient)) {
this.log(`Invalid recipient: ${recipient}`);
return false;
}
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
this.log(`Attempt ${attempt}/${this.maxRetries}`);
if (this.send(recipient, message)) {
this.sentCount++;
this.log(`Sent (total: ${this.sentCount})`);
return true;
}
this.log(`Attempt ${attempt} failed`);
}
this.log("All retries used up");
return false;
}
}
class EmailChannel extends NotificationChannel {
constructor() {
super("EMAIL");
}
send(recipient: string, message: string): boolean {
this.log(`Email to ${recipient}: ${message}`);
return true;
}
validateRecipient(recipient: string): boolean {
return recipient.includes("@") && recipient.includes(".");
}
}
// In this example the SMS gateway is busy on the first try, so the shared retry is used
class SMSChannel extends NotificationChannel {
private busyTries = 1;
constructor() {
super("SMS");
}
send(recipient: string, message: string): boolean {
if (this.busyTries > 0) {
this.busyTries--;
this.log("Gateway busy");
return false;
}
this.log(`SMS to ${recipient}: ${message.slice(0, 160)}`);
return true;
}
validateRecipient(recipient: string): boolean {
return recipient.startsWith("+") && recipient.length >= 10;
}
}
class PushChannel extends NotificationChannel {
constructor() {
super("PUSH");
}
send(recipient: string, message: string): boolean {
this.log(`Push to device ${recipient}: ${message}`);
return true;
}
validateRecipient(recipient: string): boolean {
return recipient.length === 36; // a device token written as a UUID
}
}
interface Delivery {
channel: NotificationChannel;
recipient: string;
}
// Every channel is used the same way, through the abstract class
function notifyUser(deliveries: Delivery[], message: string): void {
for (const delivery of deliveries) {
delivery.channel.sendWithRetry(delivery.recipient, message);
}
}
notifyUser(
[
{ channel: new EmailChannel(), recipient: "alice@example.com" },
{ channel: new SMSChannel(), recipient: "+1234567890" },
{ channel: new PushChannel(), recipient: "a1b2c3d4-e5f6-7890-abcd-ef1234567890" },
{ channel: new SMSChannel(), recipient: "12345" },
],
"Your order #1234 has shipped!",
);using System;
using System.Collections.Generic;
// The interface: what anything that sends a message must offer
public interface ISendable
{
bool Send(string recipient, string message);
bool ValidateRecipient(string recipient);
}
// The abstract class: the code every channel shares (its name, a count, the log and the
// retries). It leaves Send() and ValidateRecipient() to each channel
public abstract class NotificationChannel : ISendable
{
private readonly string channelName;
private readonly int maxRetries;
private int sentCount = 0;
protected NotificationChannel(string channelName, int maxRetries = 3)
{
this.channelName = channelName;
this.maxRetries = maxRetries;
}
public abstract bool Send(string recipient, string message);
public abstract bool ValidateRecipient(string recipient);
protected void Log(string text)
{
Console.WriteLine($" [{channelName}] {text}");
}
public bool SendWithRetry(string recipient, string message)
{
if (!ValidateRecipient(recipient))
{
Log($"Invalid recipient: {recipient}");
return false;
}
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
Log($"Attempt {attempt}/{maxRetries}");
if (Send(recipient, message))
{
sentCount++;
Log($"Sent (total: {sentCount})");
return true;
}
Log($"Attempt {attempt} failed");
}
Log("All retries used up");
return false;
}
}
public class EmailChannel : NotificationChannel
{
public EmailChannel() : base("EMAIL") { }
public override bool Send(string recipient, string message)
{
Log($"Email to {recipient}: {message}");
return true;
}
public override bool ValidateRecipient(string recipient) =>
recipient.Contains('@') && recipient.Contains('.');
}
// In this example the SMS gateway is busy on the first try, so the shared retry is used
public class SMSChannel : NotificationChannel
{
private int busyTries = 1;
public SMSChannel() : base("SMS") { }
public override bool Send(string recipient, string message)
{
if (busyTries > 0)
{
busyTries--;
Log("Gateway busy");
return false;
}
Log($"SMS to {recipient}: {message[..Math.Min(160, message.Length)]}");
return true;
}
public override bool ValidateRecipient(string recipient) =>
recipient.StartsWith('+') && recipient.Length >= 10;
}
public class PushChannel : NotificationChannel
{
public PushChannel() : base("PUSH") { }
public override bool Send(string recipient, string message)
{
Log($"Push to device {recipient}: {message}");
return true;
}
// a device token written as a UUID
public override bool ValidateRecipient(string recipient) => recipient.Length == 36;
}
public record Delivery(NotificationChannel Channel, string Recipient);
public static class NotifyDemo
{
// Every channel is used the same way, through the abstract class
public static void NotifyUser(List<Delivery> deliveries, string message)
{
foreach (var delivery in deliveries)
{
delivery.Channel.SendWithRetry(delivery.Recipient, message);
}
}
public static void Main()
{
NotifyUser(new List<Delivery>
{
new(new EmailChannel(), "alice@example.com"),
new(new SMSChannel(), "+1234567890"),
new(new PushChannel(), "a1b2c3d4-e5f6-7890-abcd-ef1234567890"),
new(new SMSChannel(), "12345"),
}, "Your order #1234 has shipped!");
}
}package main
import (
"fmt"
"strings"
)
// The interface: what anything that sends a message must offer
type Sendable interface {
Send(recipient, message string) bool
ValidateRecipient(recipient string) bool
}
// Go has no abstract classes. The shared state and the log sit in a base struct
// that each channel embeds, and the shared retry is a function that takes the
// channel through an interface, since an embedded struct cannot call the methods
// of the type that embeds it
type ChannelBase struct {
channelName string
maxRetries int
sentCount int
}
func (b *ChannelBase) Log(text string) {
fmt.Printf(" [%s] %s\n", b.channelName, text)
}
func (b *ChannelBase) Base() *ChannelBase {
return b
}
// NotificationChannel is the contract plus the shared base
type NotificationChannel interface {
Sendable
Base() *ChannelBase
}
func SendWithRetry(c NotificationChannel, recipient, message string) bool {
b := c.Base()
if !c.ValidateRecipient(recipient) {
b.Log("Invalid recipient: " + recipient)
return false
}
for attempt := 1; attempt <= b.maxRetries; attempt++ {
b.Log(fmt.Sprintf("Attempt %d/%d", attempt, b.maxRetries))
if c.Send(recipient, message) {
b.sentCount++
b.Log(fmt.Sprintf("Sent (total: %d)", b.sentCount))
return true
}
b.Log(fmt.Sprintf("Attempt %d failed", attempt))
}
b.Log("All retries used up")
return false
}
type EmailChannel struct{ ChannelBase }
func NewEmailChannel() *EmailChannel {
return &EmailChannel{ChannelBase{channelName: "EMAIL", maxRetries: 3}}
}
func (e *EmailChannel) Send(recipient, message string) bool {
e.Log("Email to " + recipient + ": " + message)
return true
}
func (e *EmailChannel) ValidateRecipient(recipient string) bool {
return strings.Contains(recipient, "@") && strings.Contains(recipient, ".")
}
// In this example the SMS gateway is busy on the first try, so the shared retry is used
type SMSChannel struct {
ChannelBase
busyTries int
}
func NewSMSChannel() *SMSChannel {
return &SMSChannel{ChannelBase{channelName: "SMS", maxRetries: 3}, 1}
}
func (s *SMSChannel) Send(recipient, message string) bool {
if s.busyTries > 0 {
s.busyTries--
s.Log("Gateway busy")
return false
}
s.Log("SMS to " + recipient + ": " + message[:min(160, len(message))])
return true
}
func (s *SMSChannel) ValidateRecipient(recipient string) bool {
return strings.HasPrefix(recipient, "+") && len(recipient) >= 10
}
type PushChannel struct{ ChannelBase }
func NewPushChannel() *PushChannel {
return &PushChannel{ChannelBase{channelName: "PUSH", maxRetries: 3}}
}
func (p *PushChannel) Send(recipient, message string) bool {
p.Log("Push to device " + recipient + ": " + message)
return true
}
func (p *PushChannel) ValidateRecipient(recipient string) bool {
return len(recipient) == 36 // a device token written as a UUID
}
type Delivery struct {
Channel NotificationChannel
Recipient string
}
// Every channel is used the same way, through the interface and the shared function
func NotifyUser(deliveries []Delivery, message string) {
for _, d := range deliveries {
SendWithRetry(d.Channel, d.Recipient, message)
}
}
func main() {
NotifyUser([]Delivery{
{NewEmailChannel(), "alice@example.com"},
{NewSMSChannel(), "+1234567890"},
{NewPushChannel(), "a1b2c3d4-e5f6-7890-abcd-ef1234567890"},
{NewSMSChannel(), "12345"},
}, "Your order #1234 has shipped!")
}It prints:
[EMAIL] Attempt 1/3
[EMAIL] Email to alice@example.com: Your order #1234 has shipped!
[EMAIL] Sent (total: 1)
[SMS] Attempt 1/3
[SMS] Gateway busy
[SMS] Attempt 1 failed
[SMS] Attempt 2/3
[SMS] SMS to +1234567890: Your order #1234 has shipped!
[SMS] Sent (total: 1)
[PUSH] Attempt 1/3
[PUSH] Push to device a1b2c3d4-e5f6-7890-abcd-ef1234567890: Your order #1234 has shipped!
[PUSH] Sent (total: 1)
[SMS] Invalid recipient: 12345
Every channel went through the same send_with_retry, written once in NotificationChannel. The SMS channel's first attempt failed, and the shared loop tried again without the SMS class writing any retry code of its own. The last delivery never reached send at all: the SMS channel's own validate_recipient refused 12345 first. Each channel wrote only what is really its own, the two methods Sendable asks for.
The Decision Framework
When you choose between an interface and an abstract class, ask three questions in order.
1. Do the classes share code, beyond method signatures? Shared logging, validation, state or retry logic belong in one place, so use an abstract class. If they share nothing but the signatures, use an interface.
2. Are the classes in the same family? EmailChannel, SMSChannel and PushChannel are all notification channels: they are related, and an abstract class fits. A Printer and a Logger that both have output() are not related, and an interface fits.
3. Must a class fulfil more than one contract? A class can extend only one class, so at least the extra roles must be interfaces. Often the answer is both: an abstract class that implements one or more interfaces, as NotificationChannel does.
The Java tutorial gives the same advice: consider an abstract class if "You want to share code among several closely related classes.", and an interface if "You expect that unrelated classes would implement your interface." or if "You want to take advantage of multiple inheritance of type."
Design patterns lean on both. Template Method Pattern — Algorithm Skeleton is built on an abstract class that fixes the order of the steps, and Strategy Pattern — Swappable Algorithms on an interface that every algorithm implements.
Common Mistakes
Mistake 1: an abstract class where a class needs several contracts. A PaymentProcessor extends AbstractProcessor but must also be Auditable and Refundable. Java will not let a class extend two classes: a test that wrote class C extends A, B stopped javac with '{' expected. Make Auditable and Refundable interfaces, and a class can implement both; a test of exactly that compiled and ran.
Mistake 2: an interface where classes share code. Five notification classes each implement Loggable and repeat the same logging code. Put the shared log() in an abstract class they all extend, and it is written once.
Mistake 3: an abstract class with only abstract methods. If an abstract class has no concrete methods and no state, it is an interface that also uses up the one parent each class can have. Make it an interface.
Mistake 4: treating Python's ABC as Java's interface. Python's ABC is an abstract class: it can hold state, constructors and concrete methods. Python has no interface keyword. An ABC with only abstract methods and no state plays the part of an interface, as Sendable does in the listing. Python also has Protocol in its typing module, described there as "Base class for protocol classes.": a type checker then accepts any class that has the right methods, without that class naming the protocol.
When to Use Which, and When Neither
Use an interface when:
- unrelated classes need a shared capability, as
ComparableandCloneabledo in Java; - a class must take on several roles;
- you define the contract of a design pattern, such as the strategy each algorithm implements.
Use an abstract class when:
- related classes share both a contract and code;
- you need a template whose steps subclasses fill in;
- subclasses need shared state, with fields and a constructor;
- you want default behaviour that subclasses can override.
Use neither when:
- there is only one implementation and no second in sight; a plain class is enough, as YAGNI — You Aren't Gonna Need It explains;
- the shared behaviour is small enough that holding an object that does it is simpler than inheriting it, which Composition vs Inheritance — Favor Composition takes up.
How Each Language Does It
The listing above shows each language's own way:
- Java has both keywords:
interfaceandabstract class. A classextendsone class andimplementsas many interfaces as it needs. - C# works the same way, and by custom names interfaces with a leading
I, as inISendable. - TypeScript has
interfaceandabstract classtoo. Its interfaces exist only for the type checker: the compiled listing has no trace ofSendableat all. - C++ has no interface keyword. A class with only pure virtual functions (
= 0) and no data plays that part, and a class may have several parents: a test that derived one class from two compiled and ran. - Python has no interface keyword either.
ABCfrom theabcmodule serves both purposes, and Python allows several parent classes: a test madeclass Both(Logged, Counted)and printedlogged 1. - Go has interfaces and no classes. A type satisfies an interface just by having its methods, and shared code goes into a struct that each type embeds, with a function for the part that must call the type's own methods.
The design question is the same in every language: does the common part hold shared behaviour, or only a contract?
Key Takeaways
- An interface is a contract: it lists the methods a class must offer, holds no state, and a class can take as many as it needs. In Java it may carry default, static and private methods.
- An abstract class is a partial blueprint: it can hold state, constructors and shared code beside its abstract methods, and a class extends only one.
- Ask whether the classes share code or only a contract. Shared code calls for an abstract class; a shared contract alone, for an interface.
- Often the best design uses both: an abstract class that implements an interface, as
NotificationChannelimplementsSendable. - Association — Objects That Know Each Other comes next: how objects hold references to one another.