Interfaces: The Ultimate Contract
While an Abstract Class is a "half-finished" blueprint, an Interface is a contract. It defines a set of behaviors that a class must have, but it doesn't provide any of the logic itself.
If a class "implements" an interface, it is signing a legal document saying: "I promise to provide my own version of every method listed in this interface."
1. Key Characteristics
- Multiple Implementation: Unlike classes (where you can only extend one), a class can implement multiple interfaces.
- Pure Abstraction: Traditionally, interfaces only contain abstract methods (methods with no bodies).
- Keywords: We use the
interfacekeyword to define it andimplementsto use it.
2. Interface Syntax
interface Powerable {
void turnOn(); // No body, just the requirement
void turnOff();
}
When a class signs this contract:
class Laptop implements Powerable {
@Override
public void turnOn() {
System.out.println("Displaying logo... loading OS...");
}
@Override
public void turnOff() {
System.out.println("Shutting down safely.");
}
}
3. Interfaces vs. Abstract Classes
| Feature | Abstract Class | Interface |
|---|---|---|
| Relationship | "Is-a" (A Dog is an Animal) | "Can-do" (A Plane can fly) |
| Inheritance | Single (Extends 1 only) | Multiple (Implements many) |
| Variables | Can have normal variables | Only constants (public static final) |
| Methods | Can have implemented methods | Mostly abstract (until Java 8+) |
💻 Full Practical Example: The Smart Home
Copy this code to see how one class can follow multiple "contracts":
interface Connectable {
void connectToWifi();
}
interface Alarm {
void triggerAlarm();
}
// A SmartCamera is BOTH a Connectable device AND an Alarm
class SmartCamera implements Connectable, Alarm {
@Override
public void connectToWifi() {
System.out.println("Camera connected to 'Home_Network'.");
}
@Override
public void triggerAlarm() {
System.out.println("ALERT! Motion detected! Sending notification.");
}
}
public class Main {
public static void main(String[] args) {
SmartCamera cam = new SmartCamera();
cam.connectToWifi();
cam.triggerAlarm();
}
}
4. Modern Interfaces (Default Methods)
Since Java 8, interfaces can actually have methods with bodies if you use the default keyword. This allows you to add new features to interfaces without breaking the classes that already use them.
interface Vehicle {
void move();
default void honk() {
System.out.println("Standard beep!");
}
}
💡 Challenge: The Media Player
- Create an interface
Playablewith methodsplay()andstop(). - Create an interface
Recordablewith a methodrecord(). - Create a class
Smartphonethat implements both. - Create a class
VinylPlayerthat implements onlyPlayable. - In
main, show that the Smartphone can record, but the VinylPlayer cannot.