Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 844
vach Avatar asked May 02 '26 03:05

vach


1 Answers

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.

like image 95
Rohit Jain Avatar answered May 04 '26 17:05

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!