🧭 When Should You Use an Interface?
Use an interface when:
- You want to define a contract without worrying about implementation.
It tells classes what they must do, not how to do it. - You need multiple inheritance of type.
Since Java doesn’t allow multiple class inheritance, interfaces let classes implement multiple behaviors from different sources. - You expect unrelated classes to share a common behavior.
For example, both aBird
and aDrone
mightfly()
, even though they have no common ancestor. - You want to decouple your code.
Programming to an interface (instead of a concrete class) makes your code easier to extend and test.
🛠️ How to Use an Interface
1. Define the Interface
interface Vehicle {
void start();
void stop();
}
2. Implement It in a Class
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting");
}
public void stop() {
System.out.println("Car is stopping");
}
}
3. Use the Interface as a Type
Vehicle v = new Car();
v.start(); // Output: Car is starting
This lets you swap in any Vehicle
implementation—like Bike
, Bus
, or Hovercraft
—without changing the surrounding code.
🔄 Interface vs Abstract Class: Quick Glance
Feature | Interface | Abstract Class |
---|---|---|
Inheritance | Multiple allowed | Only one superclass |
Implementation | No (until Java 8: default/static) | Yes |
Constructor | Not allowed | Allowed |
Purpose | Define what to do | Define what and how |