Implementing Multiple Interfaces
What you'll learn: How a single Java class can adopt contracts from multiple interfaces simultaneously, breaking free from single inheritance limitations.
The Power of Multiple Contracts
While Java restricts a class to extending only one superclass, it places no such limit on interfaces. A class can implement as many interfaces as needed, separated by commas. This is one of the key advantages interfaces have over abstract classes—they allow you to describe that a class fulfills multiple roles or contracts at once.
Think of it like a professional with multiple certifications: a person might be a certified teacher, a licensed driver, and a trained lifeguard. Similarly, a class can promise to fulfill several distinct contracts.
Syntax: The Comma-Separated List
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying");
}
@Override
public void swim() {
System.out.println("Duck is swimming");
}
}
The Duck class must provide implementations for all methods from both interfaces, or it must be declared abstract.
Polymorphic Flexibility
With multiple interfaces, you gain multiple type identities:
Duck duck = new Duck();
Flyable flyingThing = duck; // Valid!
Swimmable swimmingThing = duck; // Also valid!
The same object can be referenced through any of its interface types, giving you tremendous flexibility in how you pass objects around your program.
Key Takeaway: A Java class can implement multiple interfaces using comma separation (class X implements A, B, C), allowing it to fulfill multiple contracts and be used polymorphically through any of those interface types—a capability that goes beyond single class inheritance.