What are interfaces?
Lately, I’ve been looking for a new apartment in New York to move into. Over the last month i’ve seen a few co-op buildings, got interviewed and more importantly reviewed the buildings Rule books. Interfaces simply put are like co-op rule books. Just like co-up rule books don’t represent actual tenements but the rules that govern them so do interfaces. Interfaces are the rule book for all objects that implement them (or adhere to their rules).
Interfaces lists out all the public methods an object must implement. In most object oriented languages there are for types of things you can add to an object: private properties, public properties, private methods and public methods. As such, interfaces only define the rules of public API of objects.
- A DVD remote will enable us to pause, play and change volume.
- A Audio system remote will enable us to pause, play and change volume.
For both of these examples the public interface enables us to pause, play and change volume but behind the hood each of these systems are doing completely different things to make that happen. Now imagine that i’m developing a new remote (a global remote) and for our remote to support different types of systems they must have the same interface (so I can call pause, play, volume change in the same way). Luck for us both of these systems have the exact same public interface for these commands (they might have other buttons but they don’t matter to us).
An interface in programing would be like me telling all remotes that want to be supported by my global remote that they must implement 3 methods : play(), pause(), volume(num). That’s exactly what interfaces do – they don’t actually implement the methods but they tell the objects that they must have these public accessible methods and if they don’t an error ensues. If an object didn’t fully match the specs (interface), they cant move in ( usually creating a massive error the stops the execution of the program).