Conflicting Default Methods in Interface Inheritance in Java


Write a Java program to demonstrate interface inheritance with a conflicting default method

  • Both interfaces A and B have a default method sayHello().
  • The MyClass class implements both interfaces.
  • In the sayHello() method of MyClass, we resolve the conflict by explicitly specifying which interface's default method should be called using A.super.sayHello() and B.super.sayHello().
  • When we call sayHello() on an instance of MyClass, it prints "Hello from A" and "Hello from B" to the console, indicating that both default methods are invoked.

Source Code

interface A
{
	default void sayHello()
	{
		System.out.println("Hello from A");
	}
}
 
interface B
{
	default void sayHello()
	{
		System.out.println("Hello from B");
	}
}
 
class MyClass implements A, B
{
	@Override
	public void sayHello()
	{
		A.super.sayHello(); // Resolve the conflict by specifying the interface
		B.super.sayHello();
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		MyClass myClass = new MyClass();
		myClass.sayHello();
	}
}

Output

Hello from A
Hello from B

Example Programs