What Is an Interface? The Contract Metaphor
You'll learn: How Java interfaces define pure contracts that specify what a class must do without dictating how to do it.
The Core Idea
An interface in Java is a completely abstract type that defines a contract—a set of method signatures that any implementing class must provide. Think of it as a formal agreement: "If you claim to be this type, you must supply these capabilities."
Unlike abstract classes (which can mix abstract and concrete methods), interfaces traditionally contain only method declarations with no implementation details. They answer the question "what operations?" not "how are they performed?"
The Contract Metaphor
Imagine a real-world contract for a delivery service:
"Any company signing this agreement must be able to:
- Pick up a package from an address
- Deliver a package to an address
- Track a package by ID"
The contract doesn't care how you deliver (truck? drone? bicycle?). It only cares that you can deliver. Similarly, a Java interface says:
interface DeliveryService {
void pickUp(String address);
void deliver(String address);
String trackPackage(int id);
}
Any class that implements DeliveryService promises to provide these three methods. The interface enforces the "what," leaving the "how" entirely to the implementing class.
Why Contracts Matter
Interfaces let you write code that depends on capabilities rather than specific implementations. You can say "I need something that can deliver packages" without caring whether it's FedEx, UPS, or a drone startup.
This separation of contract from implementation is fundamental to flexible, maintainable design.
Key Takeaway: An interface is a pure contract defining what methods a class must implement, without specifying how—enabling polymorphism based on capabilities rather than inheritance hierarchies.