Sobes.tech
Junior — Middle

Is it possible to implement two interfaces in one class, each with default method implementations?.

sobes.tech AI

Answer from AI

Yes, in Java a class can implement multiple interfaces at once, even if these interfaces contain methods with default implementations. However, if two interfaces contain methods with the same signature, the class must override this method and explicitly specify which implementation to use or provide its own.

Example:

interface A {
    default void hello() {
        System.out.println("Hello from A");
    }
}

interface B {
    default void hello() {
        System.out.println("Hello from B");
    }
}

class C implements A, B {
    @Override
    public void hello() {
        // Explicitly choose an implementation or write your own
        A.super.hello();
        // or B.super.hello();
    }
}

Thus, the conflict of methods with default implementation is resolved by overriding in the class.

Is it possible to implement two interfaces in one… - sobes.tech