Interfaces
The Universal Adapter.
Interfaces
Analogy: hardware
An Interface is like a Power Socket.
The socket doesn't care if you plug in a TV, a Laptop, or a Blender. As long as the plug fits (implements the interface), it works!
This allows you to swap out devices without changing the wiring of your house.
The Universal Adapter
We have a Plugable interface.
- A Lamp lights up.
- A Fan spins.
- A Toaster heats up.
They all do different things, but they all fit into the same socket!
Universal Adapter (Interfaces)
Available Appliances
Interface Logic:
All these items implement the Plugable interface. The socket doesn't care what the item is, as long as it fits!
Select an appliance to plug in.
The Code
Define the "contract" (Interface):
Java Example
Switch language in Navbar
interface Plugable {
void turnOn();
void turnOff();
}
Implement it in different classes:
Java Example
Switch language in Navbar
class Lamp implements Plugable {
public void turnOn() {
System.out.println("Light!");
}
public void turnOff() {
System.out.println("Darkness...");
}
}
Up Next
Abstract Classes