0

It will awesome if I can apply a refer to a default implementation to the interface in the following program using super. Like Alpha.super.reset() so, plz tell us where this statement will be use.

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 MainClass {
  public static void main(String args[]) {
    MyClass ob = new MyClass();
    ob.reset();
    ob.display();
  }  
}

For example if we want to use the beta version of reset() method, then we have to extend one of them two interfaces. For example : interface Beta extends Alpha then it will use the beta version of reset(). But here we want to use the super and where it will be use.

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31
Manohar Kumar
  • 605
  • 9
  • 12

2 Answers2

2

The syntax for calling the default method implementation that could be coming from two different interfaces uses the name of the interface followed by .super as follows:

class MyClass implements Alpha, Beta {
    public void reset() {
        Alpha.super.reset();
        Beta.super.reset();
    }
}

This implementation of the reset() method calls the default method implementations from both interfaces.

Vukašin Manojlović
  • 3,717
  • 3
  • 19
  • 31
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Compiling your code would produce an error:

java: class MyClass inherits unrelated defaults for reset() from types alpha and beta

because the compiler cannot select a declaration to use in this conflicting situation.

Here is an article for your reference.

Owen Cao
  • 7,955
  • 2
  • 27
  • 35