vach
vach

Reputation: 11377

Java8 overriding (extending) default method

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...

Upvotes: 3

Views: 1431

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213243

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.

Upvotes: 8

Related Questions