What Is an Interface?

In software engineering, an interface is a contract or a blueprint that defines a set of methods or behaviors that a class must implement — without providing the actual implementation of those behaviors.

Think of it as a promise: “If you implement this interface, you must provide these functions.”

An interface does not contain logic. Instead, it specifies what should be done, not how. This makes it a key tool in enforcing consistency across unrelated classes and promoting polymorphism and loose coupling.

Interfaces are most commonly used in statically typed object-oriented languages like Java, C#, and TypeScript, but similar concepts exist in Python (via abstract base classes), Go (implicit interfaces), and even JavaScript (via TypeScript interfaces).

Why Interfaces Matter

  • 🔹 Encapsulation of behavior: Interfaces define behavior in a consistent way across different classes.
  • 🔹 Flexible architecture: Code can be written to depend on interfaces rather than concrete implementations.
  • 🔹 Improved testability: Interfaces enable mocking and stubbing during testing.
  • 🔹 Interoperability: Interfaces allow different classes to “speak the same language.”

Interface vs Abstract Class

FeatureInterfaceAbstract Class
Method ImplementationNo (only method signatures)Yes (can contain both abstract and concrete methods)
Multiple InheritanceSupportedNot typically supported
ConstructorNot allowedAllowed
Use CaseBehavioral contractPartial implementation + contract

Interface in Java

Declaration

public interface Vehicle {
    void start();
    void stop();
}

Implementation

public class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car is starting.");
    }

    @Override
    public void stop() {
        System.out.println("Car is stopping.");
    }
}

In this example:

  • Vehicle is the interface.
  • Car is a concrete class that commits to implementing Vehicle‘s behavior.

Interface in TypeScript

TypeScript introduces interfaces as part of its static type system for JavaScript.

interface Animal {
    name: string;
    speak(): void;
}

class Dog implements Animal {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    speak(): void {
        console.log(`${this.name} barks.`);
    }
}

Interfaces in TypeScript are purely for type checking — they do not exist at runtime.

Interface in Python (Using ABC)

Python doesn’t have “interface” as a keyword but offers ABC (Abstract Base Class) to enforce interfaces.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

Here:

  • Shape defines an interface via an abstract method.
  • Circle must implement area().

Interface in Go (Implicit Interface)

Go’s interfaces are powerful yet different: they are implicitly satisfied.

package main

import "fmt"

type Speaker interface {
    Speak()
}

type Human struct {}

func (h Human) Speak() {
    fmt.Println("Hello from Human!")
}

func greet(s Speaker) {
    s.Speak()
}

Any type that defines the required method automatically implements the interface — no implements keyword needed.

Real-World Example: Payment Gateway

Suppose you have multiple payment providers: PayPal, Stripe, and Square. Rather than writing different logic for each provider throughout your codebase, define an interface:

public interface PaymentGateway {
    boolean processPayment(double amount);
}

Each provider implements the interface:

public class StripeGateway implements PaymentGateway {
    public boolean processPayment(double amount) {
        // Stripe-specific logic
        return true;
    }
}

Now your system can accept any PaymentGateway, making it extensible and testable:

public class PaymentProcessor {
    private PaymentGateway gateway;

    public PaymentProcessor(PaymentGateway gateway) {
        this.gateway = gateway;
    }

    public void makePayment(double amount) {
        gateway.processPayment(amount);
    }
}

Benefits of Using Interfaces

  1. Decoupling
    • Promotes separation between what needs to be done and how it’s done.
  2. Substitutability
    • Enables polymorphism: an object can be replaced by another that implements the same interface.
  3. Mocking in Tests
    • In unit testing, interfaces allow for easy mocking of dependencies.
  4. Dependency Injection
    • Systems can accept dependencies through constructors or setters using interfaces.

Common Interface Patterns

Strategy Pattern

Interfaces are key in the Strategy Design Pattern, where you define interchangeable algorithms.

public interface SortingStrategy {
    void sort(int[] numbers);
}

Multiple sorting algorithms can implement this interface and be injected at runtime.

Observer Pattern

In event-driven systems:

public interface Observer {
    void update(String message);
}

Any class that wants to be notified can implement Observer.

Interface Segregation Principle (ISP)

One of the SOLID principles of software design, ISP states:

“Clients should not be forced to depend on interfaces they do not use.”

Anti-pattern:

public interface Worker {
    void work();
    void eat();
}

What if you want a RobotWorker who doesn’t eat? This violates ISP.

Solution:

Split interfaces:

public interface Workable {
    void work();
}

public interface Eatable {
    void eat();
}

Now RobotWorker can implement Workable only.

Summary

  • An interface defines a contract for what a class should do, not how it should do it.
  • It enables loose coupling, testability, polymorphism, and code reuse.
  • Used across many languages, though with differing syntax and strictness.
  • Interfaces promote scalable and maintainable architecture.

Related Keywords

  • Abstract Class
  • Polymorphism
  • Inheritance
  • Dependency Injection
  • Strategy Pattern
  • Adapter Pattern
  • SOLID Principles
  • Loose Coupling
  • Mocking
  • Type Safety
  • Abstract Base Class (ABC)
  • Protocol (Python typing)
  • Composition Over Inheritance
  • Interface Segregation Principle
  • Software Architecture
  • Design Patterns
  • Contract Programming
  • Duck Typing
  • Static Typing