Skip to main content

Abstraction — Hiding Complexity

Editorial

Introduction

Encapsulation — Data Hiding Done Right kept an object's data private and made its methods the only way to change it. That answered one question: who can reach this data? Abstraction answers a different one: what does the code that uses a class need to see?

Think about driving a car. You steer with a wheel and control the speed with two pedals. Behind them sit an engine and a gearbox, and you can drive well without knowing how either of them works. The pedals show what the car can do, and the machinery stays out of sight.

Abstraction does the same for code. A class shows what it can do through a few methods and keeps how it does it to itself. When a payment module offers process_payment(amount), the code that calls it does not need to know whether the money goes through Stripe or PayPal. Because callers depend only on that one method, the work behind it can change later without breaking them.

How Abstraction Differs from Encapsulation

The two ideas are easy to mix up, because both hide something. Encapsulation hides an object's data and guards it inside one class. Abstraction hides how a job is done, so that a whole family of classes can be used in one way.

AspectEncapsulationAbstraction
What it hidesThe data inside one classHow a job is done, across a family of classes
The question it asksWho can reach this?What must the caller see?
How code says itPrivate fields and methods that check each changeAbstract classes and interfaces
Where it livesInside one classBetween classes: a parent and its kinds
A picture of itA locked vault inside a bankAn ATM screen that shows only deposit and withdraw

In code, encapsulation sounds like this: the balance of a BankAccount is private, and you change it through deposit() and withdraw(). Abstraction sounds like this: every PaymentProcessor has a process_payment() method, and you do not need to know whether the object behind it is a StripeProcessor or a PayPalProcessor.

The two work together. Encapsulation keeps each class's data safe, and abstraction lets the code that uses those classes ignore how each one does its job.

Abstract Classes: Partial Blueprints

An abstract class is a class written to be a parent and never used on its own. The Java tutorial puts it in one line: "Abstract classes cannot be instantiated, but they can be subclassed." To instantiate a class means to make an object from it. An abstract class can hold two kinds of methods. An abstract method names a job and leaves it empty, so every subclass has to write its own version. A concrete method has a body, and every subclass shares it as it is.

Here is a small notification system built that way. Notification is abstract: it says that every notification can send(), and it shares format_message(), which puts the shop's name in front of the message. Email, text message and push notifications each write their own send(). Each language marks the abstract parts its own way, named in a comment: ABC and @abstractmethod in Python, the abstract keyword in Java, TypeScript and C#, a pure virtual method (= 0) in C++, and in Go, which has no abstract classes, an interface for the job each kind must do and an embedded struct for what they share.

from abc import ABC, abstractmethod


class Notification(ABC):
    """What every notification must do; each kind decides how. Never made directly."""

    def __init__(self, recipient: str, message: str) -> None:
        self.recipient = recipient
        self.message = message

    @abstractmethod
    def send(self) -> bool:
        """Send the notification. Each kind of notification decides how."""

    # A concrete method, shared by every kind of notification
    def format_message(self) -> str:
        return f"[ShopApp] {self.message}"


class EmailNotification(Notification):
    def __init__(self, recipient: str, message: str, subject: str) -> None:
        super().__init__(recipient, message)
        self.subject = subject

    def send(self) -> bool:
        print(f"Email to {self.recipient}")
        print(f"   Subject: {self.subject}")
        print(f"   Body: {self.format_message()}")
        return True  # real code would hand the email to a mail server here


class SMSNotification(Notification):
    def __init__(self, recipient: str, message: str, phone: str) -> None:
        super().__init__(recipient, message)
        self.phone = phone

    def send(self) -> bool:
        text = self.format_message()
        if len(text) > 160:  # this app keeps text messages to 160 characters
            text = text[:157] + "..."
        print(f"SMS to {self.phone}: {text}")
        return True  # real code would call an SMS gateway here


class PushNotification(Notification):
    def __init__(self, recipient: str, message: str, device_token: str) -> None:
        super().__init__(recipient, message)
        self.device_token = device_token

    def send(self) -> bool:
        print(f"Push to device {self.device_token[:8]}...: {self.format_message()}")
        return True  # real code would call a push service here


# The caller knows only the abstract type: it calls send() and nothing else
def notify_user(notification: Notification) -> None:
    success = notification.send()
    print(f"   Delivery: {'Success' if success else 'Failed'}")


notify_user(EmailNotification("alice", "Your order shipped!", "Order Update"))
notify_user(SMSNotification("bob", "Your code: 123456", "+1-555-0100"))
notify_user(PushNotification("charlie", "New message!", "dk3j8f9a2b"))

# Notification("test", "hello") would fail: an abstract class cannot be made directly
// What every notification must do; each kind decides how. It cannot be made directly.
abstract class Notification {
    protected final String recipient;
    protected final String message;

    protected Notification(String recipient, String message) {
        this.recipient = recipient;
        this.message = message;
    }

    // An abstract method: every kind of notification must write its own
    public abstract boolean send();

    // A concrete method, shared by every kind of notification
    public String formatMessage() {
        return "[ShopApp] " + message;
    }
}

class EmailNotification extends Notification {
    private final String subject;

    EmailNotification(String recipient, String message, String subject) {
        super(recipient, message);
        this.subject = subject;
    }

    @Override
    public boolean send() {
        System.out.println("Email to " + recipient);
        System.out.println("   Subject: " + subject);
        System.out.println("   Body: " + formatMessage());
        return true; // real code would hand the email to a mail server here
    }
}

class SMSNotification extends Notification {
    private final String phone;

    SMSNotification(String recipient, String message, String phone) {
        super(recipient, message);
        this.phone = phone;
    }

    @Override
    public boolean send() {
        String text = formatMessage();
        if (text.length() > 160) { // this app keeps text messages to 160 characters
            text = text.substring(0, 157) + "...";
        }
        System.out.println("SMS to " + phone + ": " + text);
        return true; // real code would call an SMS gateway here
    }
}

class PushNotification extends Notification {
    private final String deviceToken;

    PushNotification(String recipient, String message, String deviceToken) {
        super(recipient, message);
        this.deviceToken = deviceToken;
    }

    @Override
    public boolean send() {
        System.out.println("Push to device " + deviceToken.substring(0, 8) + "...: "
                + formatMessage());
        return true; // real code would call a push service here
    }
}

public class NotificationDemo {
    // The caller knows only the abstract type: it calls send() and nothing else
    static void notifyUser(Notification notification) {
        boolean success = notification.send();
        System.out.println("   Delivery: " + (success ? "Success" : "Failed"));
    }

    public static void main(String[] args) {
        notifyUser(
                new EmailNotification("alice", "Your order shipped!", "Order Update"));
        notifyUser(new SMSNotification("bob", "Your code: 123456", "+1-555-0100"));
        notifyUser(new PushNotification("charlie", "New message!", "dk3j8f9a2b"));

        // new Notification("test", "hello"); would not compile: the class is abstract
    }
}
#include <cstdio>
#include <memory>
#include <string>
#include <utility>

// What every notification must do; each kind decides how. A class with a pure virtual
// method is abstract in C++: it cannot be made directly.
class Notification {
public:
    Notification(std::string recipient, std::string message)
        : recipient_(std::move(recipient)), message_(std::move(message)) {}
    virtual ~Notification() = default;

    // An abstract (pure virtual) method: every kind of notification must write its own
    virtual bool send() const = 0;

    // A concrete method, shared by every kind of notification
    std::string formatMessage() const { return "[ShopApp] " + message_; }

protected:
    std::string recipient_;
    std::string message_;
};

class EmailNotification : public Notification {
public:
    EmailNotification(std::string recipient, std::string message, std::string subject)
        : Notification(std::move(recipient), std::move(message)),
          subject_(std::move(subject)) {}

    bool send() const override {
        std::printf("Email to %s\n", recipient_.c_str());
        std::printf("   Subject: %s\n", subject_.c_str());
        std::printf("   Body: %s\n", formatMessage().c_str());
        return true;  // real code would hand the email to a mail server here
    }

private:
    std::string subject_;
};

class SMSNotification : public Notification {
public:
    SMSNotification(std::string recipient, std::string message, std::string phone)
        : Notification(std::move(recipient), std::move(message)),
          phone_(std::move(phone)) {}

    bool send() const override {
        std::string text = formatMessage();
        if (text.size() > 160) {  // this app keeps text messages to 160 characters
            text = text.substr(0, 157) + "...";
        }
        std::printf("SMS to %s: %s\n", phone_.c_str(), text.c_str());
        return true;  // real code would call an SMS gateway here
    }

private:
    std::string phone_;
};

class PushNotification : public Notification {
public:
    PushNotification(std::string recipient, std::string message,
                     std::string deviceToken)
        : Notification(std::move(recipient), std::move(message)),
          deviceToken_(std::move(deviceToken)) {}

    bool send() const override {
        std::printf("Push to device %s...: %s\n", deviceToken_.substr(0, 8).c_str(),
                    formatMessage().c_str());
        return true;  // real code would call a push service here
    }

private:
    std::string deviceToken_;
};

// The caller knows only the abstract type: it calls send() and nothing else
void notifyUser(const Notification& notification) {
    bool success = notification.send();
    std::printf("   Delivery: %s\n", success ? "Success" : "Failed");
}

int main() {
    notifyUser(EmailNotification("alice", "Your order shipped!", "Order Update"));
    notifyUser(SMSNotification("bob", "Your code: 123456", "+1-555-0100"));
    notifyUser(PushNotification("charlie", "New message!", "dk3j8f9a2b"));

    // Notification n("test", "hello"); would not compile: the class is abstract
    return 0;
}
// What every notification must do; each kind decides how. It cannot be made directly.
abstract class Notification {
  constructor(
    protected readonly recipient: string,
    protected readonly message: string,
  ) {}

  // An abstract method: every kind of notification must write its own
  abstract send(): boolean;

  // A concrete method, shared by every kind of notification
  formatMessage(): string {
    return `[ShopApp] ${this.message}`;
  }
}

class EmailNotification extends Notification {
  constructor(
    recipient: string,
    message: string,
    private readonly subject: string,
  ) {
    super(recipient, message);
  }

  send(): boolean {
    console.log(`Email to ${this.recipient}`);
    console.log(`   Subject: ${this.subject}`);
    console.log(`   Body: ${this.formatMessage()}`);
    return true; // real code would hand the email to a mail server here
  }
}

class SMSNotification extends Notification {
  constructor(
    recipient: string,
    message: string,
    private readonly phone: string,
  ) {
    super(recipient, message);
  }

  send(): boolean {
    let text = this.formatMessage();
    if (text.length > 160) {
      // this app keeps text messages to 160 characters
      text = text.slice(0, 157) + "...";
    }
    console.log(`SMS to ${this.phone}: ${text}`);
    return true; // real code would call an SMS gateway here
  }
}

class PushNotification extends Notification {
  constructor(
    recipient: string,
    message: string,
    private readonly deviceToken: string,
  ) {
    super(recipient, message);
  }

  send(): boolean {
    const device = this.deviceToken.slice(0, 8);
    console.log(`Push to device ${device}...: ${this.formatMessage()}`);
    return true; // real code would call a push service here
  }
}

// The caller knows only the abstract type: it calls send() and nothing else
function notifyUser(notification: Notification): void {
  const success = notification.send();
  console.log(`   Delivery: ${success ? "Success" : "Failed"}`);
}

notifyUser(new EmailNotification("alice", "Your order shipped!", "Order Update"));
notifyUser(new SMSNotification("bob", "Your code: 123456", "+1-555-0100"));
notifyUser(new PushNotification("charlie", "New message!", "dk3j8f9a2b"));

// new Notification("test", "hello"); would not compile: the class is abstract

// Its own module, so this Notification does not clash with the browser's one
export {};
using System;

// What every notification must do; each kind decides how. It cannot be made directly.
public abstract class Notification
{
    protected readonly string Recipient;
    protected readonly string Message;

    protected Notification(string recipient, string message)
    {
        Recipient = recipient;
        Message = message;
    }

    // An abstract method: every kind of notification must write its own
    public abstract bool Send();

    // A concrete method, shared by every kind of notification
    public string FormatMessage()
    {
        return "[ShopApp] " + Message;
    }
}

public class EmailNotification : Notification
{
    private readonly string _subject;

    public EmailNotification(string recipient, string message, string subject)
        : base(recipient, message)
    {
        _subject = subject;
    }

    public override bool Send()
    {
        Console.WriteLine("Email to " + Recipient);
        Console.WriteLine("   Subject: " + _subject);
        Console.WriteLine("   Body: " + FormatMessage());
        return true; // real code would hand the email to a mail server here
    }
}

public class SMSNotification : Notification
{
    private readonly string _phone;

    public SMSNotification(string recipient, string message, string phone)
        : base(recipient, message)
    {
        _phone = phone;
    }

    public override bool Send()
    {
        string text = FormatMessage();
        if (text.Length > 160) // this app keeps text messages to 160 characters
        {
            text = text.Substring(0, 157) + "...";
        }
        Console.WriteLine("SMS to " + _phone + ": " + text);
        return true; // real code would call an SMS gateway here
    }
}

public class PushNotification : Notification
{
    private readonly string _deviceToken;

    public PushNotification(string recipient, string message, string deviceToken)
        : base(recipient, message)
    {
        _deviceToken = deviceToken;
    }

    public override bool Send()
    {
        Console.WriteLine("Push to device " + _deviceToken.Substring(0, 8) + "...: "
            + FormatMessage());
        return true; // real code would call a push service here
    }
}

public static class Program
{
    // The caller knows only the abstract type: it calls Send() and nothing else
    static void NotifyUser(Notification notification)
    {
        bool success = notification.Send();
        Console.WriteLine("   Delivery: " + (success ? "Success" : "Failed"));
    }

    public static void Main()
    {
        NotifyUser(
            new EmailNotification("alice", "Your order shipped!", "Order Update"));
        NotifyUser(new SMSNotification("bob", "Your code: 123456", "+1-555-0100"));
        NotifyUser(new PushNotification("charlie", "New message!", "dk3j8f9a2b"));

        // new Notification("test", "hello"); would not compile: the class is abstract
    }
}
package main

import "fmt"

// Notification is what every notification must do; each kind decides how. Go has no
// abstract classes: an interface says what must be done, and an embedded struct
// carries what every kind shares.
type Notification interface {
	Send() bool
}

// base holds the shared fields and the shared, concrete method
type base struct {
	recipient string
	message   string
}

func (b base) FormatMessage() string { return "[ShopApp] " + b.message }

type EmailNotification struct {
	base
	subject string
}

func (n EmailNotification) Send() bool {
	fmt.Println("Email to " + n.recipient)
	fmt.Println("   Subject: " + n.subject)
	fmt.Println("   Body: " + n.FormatMessage())
	return true // real code would hand the email to a mail server here
}

type SMSNotification struct {
	base
	phone string
}

func (n SMSNotification) Send() bool {
	text := n.FormatMessage()
	if len(text) > 160 { // this app keeps text messages to 160 characters
		text = text[:157] + "..."
	}
	fmt.Println("SMS to " + n.phone + ": " + text)
	return true // real code would call an SMS gateway here
}

type PushNotification struct {
	base
	deviceToken string
}

func (n PushNotification) Send() bool {
	fmt.Println("Push to device " + n.deviceToken[:8] + "...: " + n.FormatMessage())
	return true // real code would call a push service here
}

// notifyUser knows only the interface: it calls Send() and nothing else
func notifyUser(notification Notification) {
	result := "Failed"
	if notification.Send() {
		result = "Success"
	}
	fmt.Println("   Delivery: " + result)
}

func main() {
	notifyUser(EmailNotification{base{"alice", "Your order shipped!"}, "Order Update"})
	notifyUser(SMSNotification{base{"bob", "Your code: 123456"}, "+1-555-0100"})
	notifyUser(PushNotification{base{"charlie", "New message!"}, "dk3j8f9a2b"})
}

It prints:

Email to alice
   Subject: Order Update
   Body: [ShopApp] Your order shipped!
   Delivery: Success
SMS to +1-555-0100: [ShopApp] Your code: 123456
   Delivery: Success
Push to device dk3j8f9a...: [ShopApp] New message!
   Delivery: Success

Look at notify_user. It takes any Notification and calls send(), and that is all it knows. It cannot tell whether it was handed an email or a text message, and it does not need to. Each kind does its own work inside its own send(): the email gets a subject and a body, the text message is kept to 160 characters, and the push notification shows only the first 8 characters of the device token. Every kind takes its text from the one shared format_message(), which is why every message starts with [ShopApp].

Because notify_user depends only on send(), a new kind needs no change to it. We tried it: a SlackNotification written after this listing, with its own send(), was passed to the same notify_user and printed Slack to #orders: [ShopApp] Your order shipped! and then Delivery: Success, with not one line of notify_user changed.

The language also holds every kind to the contract. Try to make a plain Notification, and Python stops the program with a TypeError when that line runs: Can't instantiate abstract class Notification without an implementation for abstract method 'send'. Java refuses even earlier, when the code is compiled: Notification is abstract; cannot be instantiated. Python's documentation for abc gives the rule behind it: a class like this cannot be made until every one of its abstract methods is written. So a subclass that forgets its own send() cannot be made either; Python said Can't instantiate abstract class FaxNotification without an implementation for abstract method 'send'. Java handles that case at compile time. The Java tutorial says: "When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract."

The picture puts the listing together: the caller that sees only send(), the abstract class with its two kinds of method, and the kinds under it, each sending its own way.

Show what, hide how: show what it does, hide how, like pedals over an engine. The caller, notify_user(n: Notification), calls n.send() and nothing else. The abstract class Notification(ABC) is never made directly; send() is abstract, each kind writes its own, and format_message() is concrete, shared by all. Each kind is a Notification and sends in its own way: Email, with a subject and body, to a mail server; SMS, cut to 160 characters, to an SMS gateway; Push, with the first 8 characters of the device token, to a push service; and Slack, added later, with no change to the caller. Below, encapsulation beside abstraction. Encapsulation hides the data inside one class and asks who can reach it: a safe holds the private balance, and only deposit() and withdraw() reach it. Abstraction hides how a thing is done across a family of classes and asks what the caller must see: one face, Notification, with one send() button, and the gears of Email, SMS and Push behind it.

Follow a Call Through the Contract

Here is the listing's notify_user beside its abstract class, with the three kinds under it. Press Email, SMS and Push to pass each one to notify_user, and follow the call: it reaches send() on Notification, goes down to the object's own send(), fetches [ShopApp] from the shared format_message(), and lands on that kind's screen in its own way. Then press Notification("test", "hello") to try making the abstract class directly, and Add SlackNotification to watch a new kind join and work through the same caller.

notify_user calls only send(). Each kind does its own work behind it, a plain Notification is turned away, and a kind added later needs no change to the caller.

Interfaces: Contracts for Unrelated Classes

An abstract class can hold fields and shared code. Sometimes you want only the promise: a list of methods a class must have, with nothing passed down at all. That is an interface. A class that implements an interface promises to write every method the interface names.

Interfaces are often described as contracts with no code in them. In Java that is not quite true: an interface may also carry default methods, which have bodies. The Java tutorial says: "Method bodies exist only for default methods and static methods."

An interface is most useful when classes that have nothing else in common should promise the same ability. A product catalog and a user directory share no parent, yet both can be searched:

from abc import ABC, abstractmethod


# Python has no interface keyword: an abstract class of abstract methods plays that part
class Searchable(ABC):
    @abstractmethod
    def search(self, query: str) -> list[str]: ...

    @abstractmethod
    def count_results(self, query: str) -> int: ...


# Two classes with nothing else in common can both promise to be searchable
class ProductCatalog(Searchable):
    def __init__(self) -> None:
        self.products = ["Laptop", "Laptop bag", "Mouse"]

    def search(self, query: str) -> list[str]:
        return [p for p in self.products if query.lower() in p.lower()]

    def count_results(self, query: str) -> int:
        return len(self.search(query))


class UserDirectory(Searchable):
    def __init__(self) -> None:
        self.users = ["alice", "bob", "alicia"]

    def search(self, query: str) -> list[str]:
        return [u for u in self.users if query.lower() in u.lower()]

    def count_results(self, query: str) -> int:
        return len(self.search(query))


# This function needs only the contract, so it works with either class
def report(source: Searchable, name: str, query: str) -> None:
    found = ", ".join(source.search(query))
    print(f'{name}: {source.count_results(query)} results for "{query}": [{found}]')


report(ProductCatalog(), "ProductCatalog", "lap")
report(UserDirectory(), "UserDirectory", "ali")
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// An interface: this one only names what must exist, with no code of its own
interface Searchable {
    List<String> search(String query);

    int countResults(String query);
}

// Two classes with nothing else in common can both promise to be searchable
class ProductCatalog implements Searchable {
    private final List<String> products = List.of("Laptop", "Laptop bag", "Mouse");

    @Override
    public List<String> search(String query) {
        List<String> found = new ArrayList<>();
        for (String p : products) {
            if (p.toLowerCase(Locale.ROOT).contains(query.toLowerCase(Locale.ROOT))) {
                found.add(p);
            }
        }
        return found;
    }

    @Override
    public int countResults(String query) {
        return search(query).size();
    }
}

class UserDirectory implements Searchable {
    private final List<String> users = List.of("alice", "bob", "alicia");

    @Override
    public List<String> search(String query) {
        List<String> found = new ArrayList<>();
        for (String u : users) {
            if (u.toLowerCase(Locale.ROOT).contains(query.toLowerCase(Locale.ROOT))) {
                found.add(u);
            }
        }
        return found;
    }

    @Override
    public int countResults(String query) {
        return search(query).size();
    }
}

public class SearchDemo {
    // This method needs only the contract, so it works with either class
    static void report(Searchable source, String name, String query) {
        String found = String.join(", ", source.search(query));
        System.out.println(name + ": " + source.countResults(query) + " results for \""
                + query + "\": [" + found + "]");
    }

    public static void main(String[] args) {
        report(new ProductCatalog(), "ProductCatalog", "lap");
        report(new UserDirectory(), "UserDirectory", "ali");
    }
}
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>

namespace {
std::string lower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    return s;
}

std::vector<std::string> matching(const std::vector<std::string>& items,
                                  const std::string& q) {
    std::vector<std::string> found;
    for (const auto& item : items) {
        if (lower(item).find(lower(q)) != std::string::npos) found.push_back(item);
    }
    return found;
}
}  // namespace

// C++ has no interface keyword: a class with only pure virtual methods plays that part
class Searchable {
public:
    virtual ~Searchable() = default;
    virtual std::vector<std::string> search(const std::string& query) const = 0;
    virtual std::size_t countResults(const std::string& query) const = 0;
};

// Two classes with nothing else in common can both promise to be searchable
class ProductCatalog : public Searchable {
public:
    std::vector<std::string> search(const std::string& query) const override {
        return matching(products_, query);
    }
    std::size_t countResults(const std::string& query) const override {
        return search(query).size();
    }

private:
    std::vector<std::string> products_{"Laptop", "Laptop bag", "Mouse"};
};

class UserDirectory : public Searchable {
public:
    std::vector<std::string> search(const std::string& query) const override {
        return matching(users_, query);
    }
    std::size_t countResults(const std::string& query) const override {
        return search(query).size();
    }

private:
    std::vector<std::string> users_{"alice", "bob", "alicia"};
};

// This function needs only the contract, so it works with either class
void report(const Searchable& source, const std::string& name,
            const std::string& query) {
    std::string found;
    for (const auto& item : source.search(query)) {
        found += (found.empty() ? "" : ", ") + item;
    }
    std::printf("%s: %zu results for \"%s\": [%s]\n", name.c_str(),
                source.countResults(query),
                query.c_str(), found.c_str());
}

int main() {
    report(ProductCatalog(), "ProductCatalog", "lap");
    report(UserDirectory(), "UserDirectory", "ali");
    return 0;
}
// An interface: this one only names what must exist, with no code of its own
interface Searchable {
  search(query: string): string[];
  countResults(query: string): number;
}

// Two classes with nothing else in common can both promise to be searchable
class ProductCatalog implements Searchable {
  private readonly products = ["Laptop", "Laptop bag", "Mouse"];

  search(query: string): string[] {
    return this.products.filter((p) => p.toLowerCase().includes(query.toLowerCase()));
  }

  countResults(query: string): number {
    return this.search(query).length;
  }
}

class UserDirectory implements Searchable {
  private readonly users = ["alice", "bob", "alicia"];

  search(query: string): string[] {
    return this.users.filter((u) => u.toLowerCase().includes(query.toLowerCase()));
  }

  countResults(query: string): number {
    return this.search(query).length;
  }
}

// This function needs only the contract, so it works with either class
function report(source: Searchable, name: string, query: string): void {
  const found = source.search(query).join(", ");
  const count = source.countResults(query);
  console.log(`${name}: ${count} results for "${query}": [${found}]`);
}

report(new ProductCatalog(), "ProductCatalog", "lap");
report(new UserDirectory(), "UserDirectory", "ali");
using System;
using System.Collections.Generic;
using System.Linq;

// An interface: this one only names what must exist, with no code of its own
public interface ISearchable
{
    List<string> Search(string query);
    int CountResults(string query);
}

// Two classes with nothing else in common can both promise to be searchable
public class ProductCatalog : ISearchable
{
    private readonly List<string> _products = new() { "Laptop", "Laptop bag", "Mouse" };

    public List<string> Search(string query)
    {
        return _products
            .Where(p => p.Contains(query, StringComparison.OrdinalIgnoreCase))
            .ToList();
    }

    public int CountResults(string query)
    {
        return Search(query).Count;
    }
}

public class UserDirectory : ISearchable
{
    private readonly List<string> _users = new() { "alice", "bob", "alicia" };

    public List<string> Search(string query)
    {
        return _users
            .Where(u => u.Contains(query, StringComparison.OrdinalIgnoreCase))
            .ToList();
    }

    public int CountResults(string query)
    {
        return Search(query).Count;
    }
}

public static class Program
{
    // This method needs only the contract, so it works with either class
    static void Report(ISearchable source, string name, string query)
    {
        string found = string.Join(", ", source.Search(query));
        Console.WriteLine(
            $"{name}: {source.CountResults(query)} results for \"{query}\": [{found}]");
    }

    public static void Main()
    {
        Report(new ProductCatalog(), "ProductCatalog", "lap");
        Report(new UserDirectory(), "UserDirectory", "ali");
    }
}
package main

import (
	"fmt"
	"strings"
)

// Searchable is an interface: it only names what must exist. Go needs no "implements":
// any type with these two methods is a Searchable.
type Searchable interface {
	Search(query string) []string
	CountResults(query string) int
}

func matching(items []string, query string) []string {
	var found []string
	for _, item := range items {
		if strings.Contains(strings.ToLower(item), strings.ToLower(query)) {
			found = append(found, item)
		}
	}
	return found
}

// ProductCatalog and UserDirectory have nothing else in common, yet both are searchable
type ProductCatalog struct{ products []string }

func (c ProductCatalog) Search(query string) []string {
	return matching(c.products, query)
}

func (c ProductCatalog) CountResults(query string) int {
	return len(c.Search(query))
}

type UserDirectory struct{ users []string }

func (d UserDirectory) Search(query string) []string {
	return matching(d.users, query)
}

func (d UserDirectory) CountResults(query string) int {
	return len(d.Search(query))
}

// report needs only the contract, so it works with either type
func report(source Searchable, name, query string) {
	found := strings.Join(source.Search(query), ", ")
	fmt.Printf("%s: %d results for \"%s\": [%s]\n",
		name, source.CountResults(query), query, found)
}

func main() {
	catalog := ProductCatalog{[]string{"Laptop", "Laptop bag", "Mouse"}}
	report(catalog, "ProductCatalog", "lap")
	report(UserDirectory{[]string{"alice", "bob", "alicia"}}, "UserDirectory", "ali")
}

It prints:

ProductCatalog: 2 results for "lap": [Laptop, Laptop bag]
UserDirectory: 2 results for "ali": [alice, alicia]

report needs only the promise that something can be searched, so it works with either class. Each language spells that promise its own way, named in a comment: an interface in Java, TypeScript and C#, a class with only pure virtual methods in C++, and an abstract class of abstract methods in Python, which has no interface keyword. In Go a type has the interface just by having its methods. Go's FAQ explains: "A Go type implements an interface by implementing the methods of that interface, nothing more."

Which one should you reach for? The Java tutorial suggests an abstract class when "You want to share code among several closely related classes." and an interface when "You expect that unrelated classes would implement your interface." It also gives the rule about how many: "In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces."

AspectAbstract classInterface
Reach for it whenClosely related classes share codeUnrelated classes promise the same ability
Code it can shareConcrete methods and fieldsOnly default and static methods (Java)
How many a Java class can haveOne parent classAny number
The examples hereNotification and its kindsSearchable on a catalog and a directory

In Python, an abstract class whose methods are all abstract plays the part of an interface, and a class may inherit from several of them. Interfaces vs Abstract Classes compares the two in depth, and I — Interface Segregation Principle shows how to keep each interface small.

Common Mistakes

Mistake 1: an abstract class that asks for nothing. In Python, inheriting from ABC does not by itself make a class abstract; only the methods marked @abstractmethod do. Leave the mark off send() and two things go wrong at once, as a small test on the listing's classes showed. A plain Notification("test", "hello") is made without a word of complaint. And a FaxNotification that forgot to write its own send() runs the parent's empty one, so notify_user printed Delivery: Failed and raised no error at all. Mark every method that each kind must write as abstract, so that a forgotten one fails at once and loudly.

Java does allow an abstract class with no abstract methods; the Java tutorial says an abstract class "may or may not include abstract methods". Such a class still cannot be made directly, which is sometimes what you want for a parent meant only for subclasses. If you write one, let that be the reason.

Mistake 2: an abstract method that gives away how the work is done. An abstract method should name the job and leave the means to each kind. This one does the opposite:

@abstractmethod
def send_via_smtp(self, smtp_server: str) -> bool: ...

It makes every kind send through an SMTP mail server, which means nothing to a text message or a push notification. Name the job instead, and let each kind decide how:

@abstractmethod
def send(self) -> bool: ...

Mistake 3: abstracting too early. An abstract class with a single kind under it adds a layer that every reader has to look through, and it gives nothing back until a second kind arrives. Write the abstract class when you have two or more kinds, or when you know another one is coming. Until then, a plain class is easier to read and just as easy to change later. YAGNI — You Aren't Gonna Need It covers this habit in full.

Key Takeaways

  • Abstraction shows the code that uses a class what the class can do and keeps how it does it out of sight. A caller such as notify_user depends on send() alone.
  • An abstract class is never made directly. A subclass can be made only once it writes every abstract method, and all the subclasses share the concrete ones.
  • An interface is a promise of methods that unrelated classes can make. In Java it may also carry default methods, and a class can implement any number of interfaces.
  • Encapsulation hides the data inside one class; abstraction hides how the work is done across a family of classes.
  • Inheritance — Code Reuse & Hierarchies comes next: how a subclass takes on its parent's fields and methods.