Write a Java program to diamond problem in multiple inheritance


This Java program demonstrates the resolution of the diamond problem using the super keyword when multiple interfaces provide a default implementation of a method, and a class implements those interfaces. The diamond problem occurs when a class inherits from two or more classes or interfaces that have a common method with the same name. Here's an explanation of the program:

  • public class Main: This is the main class that contains the main method, which serves as the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution begins.
  • D d = new D();: An instance of the D class is created.
  • d.display();: The display method is called on the d object.
  • interface A: This is the A interface, which provides a default implementation of the display method, printing "Interface A."
  • interface B extends A: The B interface extends A and provides a default implementation of the display method, printing "Interface B."
  • interface C extends A: The C interface also extends A and provides a default implementation of the display method, printing "Interface C."
  • class D implements B, C: The D class implements both the B and C interfaces, which both inherit from A. This creates the diamond problem because both B and C provide a default implementation of the display method.
  • @Override public void display(): The D class overrides the display method from both the B and C interfaces to provide its own implementation.
  • B.super.display();: Within the D class's display method, it uses B.super.display() to specify that it wants to call the display method provided by the B interface. This resolves the diamond problem by indicating which interface's method to call.
  • C.super.display();: Similarly, the D class uses C.super.display() to specify that it wants to call the display method provided by the C interface.

When the display method is called on an instance of the D class, it prints "Interface B" and "Interface C" to the console, as specified by the calls to B.super.display() and C.super.display(). This demonstrates how the diamond problem is resolved by explicitly specifying which interface's method should be invoked.


Source Code

public class Main
{
	public static void main(String[] args)
	{
		D d = new D();
		d.display();
	}
}
 
interface A
{
	default void display()
	{
		System.out.println("Interface A");
	}
}
 
interface B extends A
{
	default void display()
	{
		System.out.println("Interface B");
	}
}
 
interface C extends A
{
	default void display()
	{
		System.out.println("Interface C");
	}
}
 
class D implements B, C
{
	@Override
	public void display()
	{
		B.super.display(); // Resolving the diamond problem by specifying which interface's method to call
		C.super.display();
	}
}

Output

Interface B
Interface C