Interfaces
Overview
An Interface is a strict contract. It is a list of empty methods. If a class decides to `implement` an interface, it is signing a legal contract promising to write the code for every single method listed in that interface.
Why use them? Java only lets a class have ONE parent (`extends`). But a class can sign MULTIPLE contracts (`implements`). An interface defines *what* a class can do, completely separate from *how* it does it.
1. Pure Abstraction
Historically, interfaces contained absolutely no code. Just method names and return types. (Note: Modern Java allows some default code, but the concept remains the same).
2. Multiple Implementation
A `Duck` class can extend `Animal`, but it can also implement the `Flyable` and `Swimmable` interfaces. It gives us incredible flexibility.
Syntax
The Drone class signs the Flyable contract, meaning it MUST write the fly() method.
// The Contract
public interface Flyable {
void fly(); // No code here!
}
// The Drone signs the contract using 'implements'
public class Drone implements Flyable {
// It must fulfill the contract
@Override
public void fly() {
System.out.println("Spinning propellers and lifting off!");
}
}Common Pitfalls
- Trying to declare normal variables inside an Interface. All variables in an interface are instantly locked as `public static final` constants by Java.
- Forgetting to use the `public` keyword when you implement an interface method in your class.
Interview Tips
- Understand the difference: You `extend` an Abstract Class (which can have variables and some real code). You `implement` an Interface (which is purely a contract of actions).
Real-World Example
Interfaces are the secret to plugging different systems together. A `Database` interface might require a `save()` method. You can build a `MySQLDatabase` or a `MongoDBDatabase` and they will seamlessly swap out because they follow the same contract.
public interface DataStorage {
void saveUser(String name);
}
public class CloudStorage implements DataStorage {
@Override
public void saveUser(String name) {
System.out.println("Uploading " + name + " to the cloud.");
}
}