3

Suppose we have a default method in a interface, in implementing class if we need to add some additional logic besides the one the default method already does we have to copy the whole method? is there any possibility to reuse default method... like we do with abstract class

super.method()
// then our stuff...
vach
  • 10,571
  • 12
  • 68
  • 106

1 Answers1

8

You can invoke it like this:

interface Test {
    public default void method() {
        System.out.println("Default method called");
    }
}

class TestImpl implements Test {
    @Override
    public void method() {
        Test.super.method();
        // Class specific logic here.
    }
}

This way, you can easily decide which interface default method to invoke, by qualifying super with the interface name:

class TestImpl implements A, B {
    @Override
    public void method() {
        A.super.method();  // Call interface A method
        B.super.method();  // Call interface B method
    }
}

This is the case why super.method() won't work. As it would be ambiguous call in case the class implements multiple interfaces.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525