Skip to content
BENIBIX Learn

Interface (Programming)

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Interface, Protocol, Contract

A list of methods a class promises to have. It holds no code inside.

Think of it like

Think of it like the shape of a plug. Any lamp with that plug fits the socket.

Example

Jack's drawing app asks for any Shape that has an area method. Circle and Square both fill it in, so either one works.

Why it matters

Interfaces let parts of a program depend on promises, not on one exact class. That makes swapping parts easy.

Definition

An interface is a list of methods a class promises to have. It does not say how they work. Any class that fills in those methods can be used where the interface is asked for. This lets you swap one class for another. Java, C# and TypeScript have them built in; Python has a close idea called a protocol. It says what a thing can do, not what it is.

Example code

typescript
interface Shape {
  area(): number;
}
Anything that is a Shape must have an area method that gives a number.

Common mistake

Writing an interface that only one class will ever fill in. It adds a layer with nothing to swap.

Key takeaways

  1. 1
    A promise. These methods will exist.
  2. 2
    No code inside. Each class fills it in.
  3. 3
    Easy to swap. Any match will do.