How does a class implement several interfaces at once, and what happens when two of them define the same method?
A class can implement any number of interfaces, and each one it lists is a separate promise it has to keep. The compiler checks all of them, so if a class declares an interface but does not supply its abstract methods, the code does not compile.
public class Main {
public static void main(String[] args) {
Employee e = new Employee();
System.out.println(e.work());
System.out.println(e.report());
}
}
interface Worker {
String work();
}
interface Reporter {
String report();
}
class Employee implements Worker, Reporter {
public String work() { return "working"; }
public String report() { return "reporting"; }
}The example is the easy case, where the interfaces do not overlap. The employee satisfies both contracts, and the output shows both behaviours being available. The class can be passed to code that expects a Worker, to code that expects a Reporter, or to code that expects both.
The interesting case is overlap. Two interfaces can both supply a default method with the same signature, and if a class implements both, the compiler reports that the inherited method is ambiguous. The class has to resolve it, either by overriding the method itself or by naming one of the parents explicitly with the qualified super form.
That requirement is deliberate. It means the class author, who is the person who knows all the contexts the class will be used in, decides which behaviour applies, rather than the compiler applying an ordering rule that nobody remembers.