Java 8最有用的功能之一是default
接口上的新方法.基本上有两个原因(可能还有其他原因)为什么会被引入:
Iterator.remove()
Iterable.forEach()
从API设计者的角度来看,我希望能够在接口方法上使用其他修饰符,例如final
.在添加便捷方法时,这将非常有用,可防止在实现类时出现"意外"覆盖:
interface Sender {
// Convenience method to send an empty message
default final void send() {
send(null);
}
// Implementations should only implement this method
void send(String message);
}
Run Code Online (Sandbox Code Playgroud)
如果Sender
是一个类,上面已经是常见的做法:
abstract class Sender {
// Convenience method to send an empty message
final void send() {
send(null);
}
// Implementations should only implement this method
abstract void send(String message);
}
Run Code Online (Sandbox Code Playgroud)
现在,default
并final
有明显矛盾的关键字,但默认关键字本身不会一直严格要求 …
Java有计划default method
替代 Abstract Class
吗?我找不到使用默认方法而不是抽象的真实案例?
我在几个名为Mixin 的代码库类中看到过类似的注释:
//Mixin style implementation
public class DetachableMixin implements Detachable {}
Run Code Online (Sandbox Code Playgroud)
这种实现方式下的概念是什么?