Sub topic 15
When Two Defaults Collide
A class can implement many interfaces. Each of those interfaces can give a method a default body. Sometimes two interfaces give a default body to the same method, and Java has to decide which one the class uses. This chapter shows what happens in that case and how you fix it.
The Problem
A default method is an interface method that has a body. A class that implements the interface gets this body for free. A conflict happens when a class gets two default bodies for the same method, with the same name and the same parameters, from two unrelated interfaces.
Java will not guess which body you meant. It stops with a compile error, which is an error the compiler reports before the program can run.
The Fix: Override the Method
To fix the conflict, write your own version of the method in the class. Once the class has its own move(), Java has no choice left to make, because a method written in the class always wins over a default.
Inside your version, you can still call one of the inherited bodies. The syntax is InterfaceName.super.method(). It means "run the default body from this interface."
interface Walker {
default String move() {
return "walk";
}
}
interface Swimmer {
default String move() {
return "swim";
}
}
class Duck implements Walker, Swimmer {
@Override
public String move() {
return Walker.super.move() + " and " + Swimmer.super.move();
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Duck().move()); // prints: walk and swim
}
}Here Duck uses both bodies. You could also pick just one, as in return Swimmer.super.move();, or write something new.
Two Simple Rules
Java uses these rules to decide which method a class gets:
| Situation | Who wins |
|---|---|
| The class (or a superclass) has its own method | The class method always wins |
| One interface extends the other and overrides the default | The more specific interface wins |
| Two unrelated interfaces both have a default | Nobody wins, so you must override |
For example, suppose interface FastWalker extends Walker and gives its own move() default. A class that implements both gets the FastWalker version with no error.
Exercise
If you delete the move() method from Duck, what happens when you compile the program?
Show answer
You get a compile error. Duck inherits unrelated default bodies of move() from Walker and Swimmer, and Java will not choose between them. You must override move() in Duck.
Exercise
Rewrite Duck's move() so that it returns only the Swimmer version.
Show answer
Use @Override public String move() { return Swimmer.super.move(); }. It returns "swim".