Interfaces & Abstract Classes
Interfaces — A Promise to the World
An interface is like a job description. It says "whoever takes this job must be able to do X, Y, and Z" — but it doesn't say how. Any class that implements the interface is making a promise: "I will provide all these methods."
Why is this powerful? Because other code can work with the interface without caring about the specific class. A Printable interface doesn't care if it's printing a Document, a Photo, or a Receipt — as long as they all have a print() method. Java's built-in interfaces like Comparable power data structures such as binary search trees and sorted collections.
Key differences from classes:
- Interfaces can't have constructors or instance fields (only constants).
- A class can implement multiple interfaces (unlike extends, which is limited to one).
- Since Java 8, interfaces can have
defaultmethods with a body.
Defining & Implementing Interfaces
Default Methods & Abstract vs Interface
Since Java 8, interfaces can include default methods — methods with a body that classes inherit for free. This lets you add new methods to an interface without breaking all existing implementations.
When to use which?
- Use an interface when you want to define a capability that many unrelated classes can share. Think "can fly" (
Flyable), "can be serialized" (Serializable). - Use an abstract class when you have a family of related classes that share common code. Think "all animals eat and sleep, but make different sounds."
- Use both together when you need shared behavior (abstract class) plus additional capabilities (interfaces).
Default Methods & Combining Abstract + Interface
Bird IS an Animal (abstract class) and CAN Fly (interface). A Plane IS a Vehicle and also CAN Fly. The Flyable interface connects unrelated things that share a capability.