Search code examples
javainterfacejava-8default-method

What happens, if two interfaces contain the same default method?


If I have two interface with the same default method and both are implementing with a class/ See this program.

interface alpha {
  default void reset() {
    System.out.println("This is alpha version of default");
  }
}

interface beta {
  default void reset() {
    System.out.println("This is beta version of default");
  }
}

class MyClass implements alpha, beta {
  void display() {
    System.out.println("This is not default");
  }
}

class main_class {
  public static void main(String args[]) {
    MyClass ob = new MyClass();
    ob.reset();
    ob.display();
  }  
}

then what will happen? And also I am getting unrelated error with this program.


Solution

  • You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class)

    . You can solve it by implementing the method E.g.

    class MyClass implements alpha, beta {
      void display() {
        System.out.println("This is not default");
      }
    
      @Override
      public void reset() {
        //in order to call alpha's reset
        alpha.super.reset();
        //if you want to call beta's reset 
        beta.super.reset();
    
      }
    }