Combining Abstract and Default Methods from Multiple Interfaces
What you'll learn: How a class must fulfill all abstract contracts while inheriting compatible default implementations when implementing multiple interfaces.
The Core Idea
When a class implements multiple interfaces, it must provide implementations for all abstract methods declared across those interfaces. At the same time, it automatically inherits all default methods from those interfaces—unless there's a conflict.
Think of it like signing multiple job contracts: you must complete all the required tasks (abstract methods) from each contract, but you also get to use any standard equipment or procedures (default methods) each employer provides—as long as they don't contradict each other.
How It Works
interface Flyable {
void fly(); // Abstract method
default void move() {
System.out.println("Moving through air");
}
}
interface Swimmable {
void swim(); // Abstract method
default void rest() {
System.out.println("Resting on water");
}
}
class Duck implements Flyable, Swimmable {
// Must implement BOTH abstract methods
@Override
public void fly() {
System.out.println("Duck is flying");
}
@Override
public void swim() {
System.out.println("Duck is swimming");
}
// Inherits move() from Flyable automatically
// Inherits rest() from Swimmable automatically
}
The Duck class must override both fly() and swim() (the abstract methods). However, it automatically gains move() and rest() (the default methods) without writing any additional code.
What Happens
- Abstract methods from all interfaces create mandatory obligations
- Default methods with unique names are inherited seamlessly
- You can override inherited default methods if needed
- Conflicts between default methods require explicit resolution (covered previously)
Key Takeaway:
When implementing multiple interfaces, you must satisfy every abstract method contract while automatically inheriting all compatible default methods—combining obligations with conveniences.