Java8重写(扩展)默认方法

vac*_*ach 2 interface java-8 default-method

假设我们在接口中有一个默认方法,在实现类时如果我们需要添加一些额外的逻辑,除了我们必须复制整个方法的默认方法之外?是否有可能重用默认方法...就像我们使用抽象类一样

super.method()
// then our stuff...
Run Code Online (Sandbox Code Playgroud)

Roh*_*ain 7

你可以像这样调用它:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以通过super使用接口名称限定来轻松决定要调用的接口默认方法:

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

这就是为什么super.method()不起作用的情况.因为如果类实现多个接口,它将是模糊的调用.