Interfaces
Interfaces
Section titled “Interfaces”Introduction
Section titled “Introduction”An interface is a contract that defines a set of methods that implementing classes must provide. It specifies what a class should do, but not how it should do it.
Interfaces enable abstraction and polymorphism without implementation details.
Real-World Analogy: USB Port
Section titled “Real-World Analogy: USB Port”A USB port is an interface:
- USB defines: “You must transfer data using this protocol”
- Devices implement: Flash drives, keyboards, phones (all implement USB)
- Benefit: Any USB device works with any USB port
Interface vs Abstract Class
Section titled “Interface vs Abstract Class”| Aspect | Interface | Abstract Class |
|---|---|---|
| Purpose | Contract (what to do) | Partial implementation (what + how) |
| Methods | All abstract (traditionally) | Mix of abstract and concrete |
| State | No instance state | Can have fields/state |
| Constructors | No | Yes |
| Multiple inheritance | Yes (implement many) | No (extend one) |
Code Examples
Section titled “Code Examples”interface Loggable { log(message: string): void;}
class ConsoleLogger implements Loggable { log(message: string): void { console.log(`[LOG]: ${message}`); }}
class FileLogger implements Loggable { constructor(private filename: string) {} log(message: string): void { console.log(`Writing to ${this.filename}: ${message}`); }}from abc import ABC, abstractmethod
class Drawable(ABC): @abstractmethod def draw(self) -> str: pass
@abstractmethod def get_area(self) -> float: pass
class Circle(Drawable): def __init__(self, radius): self.radius = radius def draw(self) -> str: return f"Drawing circle with radius {self.radius}" def get_area(self) -> float: return 3.14159 * self.radius ** 2Best Practices
Section titled “Best Practices”- Follow Interface Segregation — small, focused interfaces
- Program to interfaces in your public API
- Prefer interfaces over abstract classes for defining contracts
Previous Topic: Static Members → Next Topic: Abstract Classes →