An interface defines a contract — a set of method signatures a class promises to implement — without providing any implementation itself. It describes what a class can do, with no opinion about how. Any class that implements an interface guarantees it provides all the methods that interface requires.
interface Playable {
function play(): void
function pause(): void
function stop(): void
}
class MusicTrack implements Playable {
function play(): void { print("Playing music...") }
function pause(): void { print("Music paused.") }
function stop(): void { print("Music stopped.") }
}
class VideoClip implements Playable {
function play(): void { print("Playing video...") }
function pause(): void { print("Video paused.") }
function stop(): void { print("Video stopped.") }
}
function controlMedia(Playable media) {
media.play() // works with anything that implements Playable
}
controlMedia(new MusicTrack())
controlMedia(new VideoClip())
controlMedia() doesn't need to know whether it received a MusicTrack or a VideoClip — it only needs to know the object satisfies the Playable contract. This is polymorphism enabled through interfaces rather than inheritance.
A class can implement multiple interfaces, unlike single inheritance:
class SmartSpeaker implements Playable, Connectable, VoiceControllable {
// must implement every method required by all three interfaces
}
This is one of the main reasons interfaces exist even in languages that already support inheritance: they let you compose multiple independent capabilities onto one class, something single inheritance alone cannot do cleanly.