Python Interfaces, Abstract Classes & Polymorphism
Build loosely-coupled, extensible architectures. Learn pure contract interfaces (interface, implements), partial implementations with abstract classes, multiple interface inheritance, and polymorphic dependency injection.
"An interface is like a universal electrical wall outlet standard: any lamp, laptop charger, or blender that matches the 3-prong interface can plug in and draw power without caring how the power company generates the electricity."
Deep Dive: How It Works
Interfaces: Pure contracts declaring method signatures without implementations (e.g. interface Logger { public function log(string $msg): void; }).
Abstract Classes: Classes that cannot be instantiated directly and can contain both concrete methods and abstract method signatures.
Multiple Interfaces: A single class can implement multiple interfaces (class Repository implements Reader, Writer).
Polymorphism: Functions accept interface type hints, allowing arbitrary implementations to be passed interchangeable.
Syntax Blueprint
<?php
interface PaymentGateway {
public function charge(float $amount): bool;
}
class StripeGateway implements PaymentGateway {
public function charge(float $amount): bool { return true; }
}Define contract with interface and implement all methods in concrete classes with implements.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Declaring non-public methods in an interface.Why it happens: Interface methods are contracts by definition and must always be public.
How to fix: All methods declared inside an interface must be public.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Implement Renderable Interface
Define an interface Renderable with public function render(): string;.
Create a class Button implements Renderable with public function __construct(public string $label) {}.
Implement render() returning "<button>{$this->label}</button>".
In main, create $btn = new Button("Submit") and print $btn->render().
Finished reading and practicing?
Mark this lesson as completed to update your course progress.