How to deal with the diamond problem in Java

Hi, in this tutorial we are going to see how we can deal with the diamond problem in Java. However, Java does not support multiple inheritance in order to avoid the diamond problem that we are going to discuss now.

For example- here are two classes named A and B, which are being inherited in a third class named C. So when we compile the program we got an error. See the code below:

class a 
{
   public void animal()
   {
    System.out.println("Hello this animal belongs to class a");
   }
}
class b 
{
   public void animal()
   {
     System.out.println("Hello this animal belongs to class b");
   }
}
class c extends a,b
{
   public static void main(String ar[])
   {
     c obj=new c();
     obj.animal();
   }
}

Output:

c.java:15: error: '{' expected
class c extends a,b
                 ^
1 error

Diamond problem due to interfaces in Java

However, multiple inheritance can be achieved by using interfaces in Java. Before Java 8, the method belonging to an interface cannot have any definition but after, Java 8 interface methods can have a default implementation. And when we use interfaces to achieve multiple inheritance it may give rise to the diamond problem. See the code below:

interface b 
{
  default void sum()
  {
    System.out.println("Hello this is interface b");
  }
}
interface c 
{
  default void sum()
  {
    System.out.println("Hello this is interface c");
  }
}
class fifth implements b,c
{
  
  public static void main(String ar[])
  {
    fifth obj=new fifth();
    obj.sum();
  }
}

Output:

fifth.java:15: error: types b and c are incompatible;
class fifth implements b,c
^
  class fifth inherits unrelated defaults for sum() from types b and c
1 error

The solution to this problem

So, to avoid this situation we need to override the method sum inside class fifth, from there we can call interface and version of sum method using super keyword. See the code below:

interface a
{
  public void sum();
}
interface b extends a
{
  default void sum()
  {
    System.out.println("Hello this is interface b");
  }
}
interface c extends a
{
  default void sum()
  {
    System.out.println("Hello this is interface c");
  }
}
class fifth implements b,c
{
  public void sum()
  {
    System.out.println("Hello this is class fifth");
    b.super.sum();
    c.super.sum();
  }	

  public static void main(String ar[])
  {
    fifth obj=new fifth();
    obj.sum();
  }
}
  

Output:

Hello this is class fifth
Hello this is interface b
Hello this is interface c

Also, read: Making an image blur in java

Leave a Reply