Sub topic 15
When Two Defaults Collide
In the last chapters you saw two separate ideas. A class can implement many interfaces. An interface can also give a method a body by using a default method, which is a method with code inside it that implementing classes get for free. This chapter covers what happens when you put those two ideas together and two interfaces hand your class two different bodies for the same method.
The Problem: Two Bodies, One Name
Think about a duck. It can walk, and it can swim. Say you have one interface for each skill.
interface Walker {
default String move() {
return "walk";
}
}
interface Swimmer {
default String move() {
return "swim";
}
}Both interfaces have a default method called move(). The two methods have the same name and the same parameters, which here means none. Their bodies are different.
Now you write a Duck class that implements both:
interface Walker {
default String move() {
return "walk";
}
}
interface Swimmer {
default String move() {
return "swim";
}
}
class Duck implements Walker, Swimmer {
}
public class Main {
public static void main(String[] args) {
System.out.println(new Duck().move());
}
}If you call new Duck().move(), should it return "walk" or "swim"? Java will not guess. This program does not compile. The compiler prints an error like this one:
error: types Walker and Swimmer are incompatible;
class Duck inherits unrelated defaults for move() from types Walker and SwimmerA conflict is a case where a class gets two or more possible bodies for the same method and Java cannot pick one. The word "unrelated" in the error is important. It means neither interface extends the other, so neither one is more specific.
The Fix: Override the Method
To fix the conflict, the class writes its own version of move(). When the class has its own version, Java uses that one. There is nothing left to choose between.
Inside your version, you can still reach either interface's default body. You use this special form:
InterfaceName.super.method()Walker.super.move() means "run the move() body that Walker provides." It is like calling super.move() for a parent class. The difference is that you name which interface you mean.
Here is the full, working program:
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
}
}The Duck calls both inherited versions and joins them. You have other choices too:
- Call only one of them:
return Swimmer.super.move(); - Ignore both and write something new:
return "waddle"; - Mix them with your own code, as shown above.
Rules for `InterfaceName.super`
The X.super.method() form has a few limits that beginners often hit:
Xmust be an interface that your class directly lists afterimplements. You cannot use it to reach an interface higher up the chain.- You can only use it inside an instance method of the class, because it works on the current object.
- It only calls default methods. If the method is abstract in
X, there is no body to call.
Java's Three Rules for Picking a Method
Not every case of "same method from two places" is a conflict. Java works through three rules in order, and the first rule that gives an answer wins.
- Classes win. If the class or any of its superclasses has the method, that version is used. Every interface default is ignored.
- More specific interfaces win. If one interface extends the other, the child interface's default is used.
- Otherwise, you must override. If neither rule gives an answer, the code does not compile until you write your own method.
Rule 1 in Action: Classes Win
interface Walker {
default String move() {
return "walk";
}
}
class Animal {
public String move() {
return "run";
}
}
class Dog extends Animal implements Walker {
}
public class Main {
public static void main(String[] args) {
System.out.println(new Dog().move()); // prints: run
}
}Dog gets move() from its superclass Animal and also from Walker. The class version wins, so the result is "run". There is no error. A default method is a fallback. It only fills a gap when no class provides the method.
Rule 2 in Action: More Specific Wins
interface Walker {
default String move() {
return "walk";
}
}
interface FastWalker extends Walker {
@Override
default String move() {
return "sprint";
}
}
class Cheetah implements Walker, FastWalker {
}
public class Main {
public static void main(String[] args) {
System.out.println(new Cheetah().move()); // prints: sprint
}
}FastWalker extends Walker, so FastWalker is more specific. It already replaced Walker's version. Java picks "sprint", and the program compiles fine.
Edge Cases Worth Knowing
The table sums up the common situations.
| Situation | What happens |
|---|---|
| Two unrelated interfaces, both with a default `move()` | Compile error until you override |
| A superclass has `move()`, and an interface has a default `move()` | Superclass version wins |
| Interface B extends A, and both have a default `move()` | B's version wins |
| One interface has a default `move()`, and another has an abstract `move()` | Compile error until you override |
| Two interfaces, both with an abstract `move()` | No conflict. You must implement `move()` once anyway |
The fourth row surprises many people. You might expect Java to just use the one body it has. It does not. One interface says "here is a body" and the other says "the class must supply a body." Java treats that as a conflict, so you must override.
A conflict can also come from return types. Suppose one interface has default String move() and the other has default int move(). No class can implement both, because one method cannot return two types. Overriding does not help in this case. You have to redesign one of the interfaces.
Summary
- A conflict happens when a class inherits two default bodies for the same method from unrelated interfaces.
- You fix it by overriding the method in the class and making it
public. - Inside the override,
InterfaceName.super.method()calls a specific interface's default. - Java checks in this order: the class wins, then the more specific interface wins, and otherwise you must override.
Exercise
Interfaces Printer and Scanner both declare default String status() { ... }, returning "printing" and "scanning". Neither extends the other. Write a class OfficeMachine that implements both, compiles, and returns "scanning" from status().
Show answer
The class must override status(), make it public, and call the Scanner version: class OfficeMachine implements Printer, Scanner { @Override public String status() { return Scanner.super.status(); } }. Without the override, the compiler reports that OfficeMachine inherits unrelated defaults for status().
Exercise
Class Robot has public String move() { return "roll"; }. Class Droid extends Robot implements Walker, where Walker has default String move() { return "walk"; }. Does Droid compile, and what does new Droid().move() return?
Show answer
It compiles and returns "roll". Under rule 1, a method from a class or superclass always beats an interface default, so there is no conflict.
Exercise
Interface A has default void go() {}, and interface B has the abstract method void go();. A class C implements A, B has no go() method. Does it compile? Why?
Show answer
No. A default method and an abstract method with the same signature from unrelated interfaces count as a conflict. Class C must declare its own public void go(). Inside it, C can call A.super.go() if it wants the default behavior.