Senior
```java // 2 public class Interfaces { public static void main(String[] args) { A a = new A() {}; B b = new B() {}; AB ab = new AB(); a.print(); b.print(); ab.print(); } public interface A { default void print() { System.out.println("interface A"); } } public interface B extends A { default void print() { System.out.println("interface B"); } } public static class AB implements A, B { } } ```
sobes.tech AI
Answer from AI
In this code, there are interfaces A and B, where B extends A and overrides the print() method. The class AB implements both interfaces A and B but does not override the print() method.
When calling methods:
A a = new A() {};— anonymous implementation of interface A, callinga.print()will output "interface A".B b = new B() {};— anonymous implementation of interface B, callingb.print()will output "interface B".AB ab = new AB();— class AB implements both interfaces but does not override print(). In case of conflicts with default methods during multiple inheritance of interfaces in Java, the class must explicitly override the method to resolve the conflict. Since it does not, the code will not compile.
If you add an explicit override of the print() method in class AB, for example:
@Override
public void print() {
B.super.print(); // or A.super.print();
}
then calling ab.print() will output "interface B" (if B.super.print() is chosen).
Summary:
- The code will not compile due to conflicts of default methods in AB.
- You need to explicitly override print() in AB to resolve the conflict.
Example fix:
public static class AB implements A, B {
@Override
public void print() {
B.super.print();
}
}