【发布时间】:2023-03-04 19:20:02
【问题描述】:
假设我们在一个接口中有一个默认方法, 在实现类中,如果我们需要添加一些额外的逻辑,除了默认方法之外,我们是否必须复制整个方法?是否有可能重用默认方法...就像我们对抽象类所做的那样
super.method()
// then our stuff...
【问题讨论】:
标签: interface java-8 default-method
假设我们在一个接口中有一个默认方法, 在实现类中,如果我们需要添加一些额外的逻辑,除了默认方法之外,我们是否必须复制整个方法?是否有可能重用默认方法...就像我们对抽象类所做的那样
super.method()
// then our stuff...
【问题讨论】:
标签: interface java-8 default-method
你可以这样调用它:
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.
}
}
这样,您可以通过使用接口名称限定super,轻松决定调用哪个接口默认方法:
class TestImpl implements A, B {
@Override
public void method() {
A.super.method(); // Call interface A method
B.super.method(); // Call interface B method
}
}
这就是super.method() 不起作用的原因。因为如果类实现多个接口,这将是模棱两可的调用。
【讨论】: