今天在看druid.io的源码的时候,发现在接口中竟然可以是用default关键字,并且可以在接口中实现方法体.查询资料发现default是JDK1.8中新增的,这种发破了原来java对接口语法的闲置.
public interface Jobby {
boolean run();
/**
* @return A map containing statistics for a Jobby, optionally null if the Jobby is unable to provide stats.
*/
@Nullable
default Map<String, Object> getStats() {
throw new UOE("This Jobby does not implement getJobStats(), Jobby class: [%s]", getClass());
}
/**
* @return A string representing the error that caused a Jobby to fail. Can be null if the Jobby did not fail,
* or is unable to provide an error message.
*/
@Nullable
default String getErrorMessage() {
throw new UOE("This Jobby does not implement getErrorMessage(), Jobby class: [%s]", getClass());
}
}
我在在做接口编程的时候,如果在接口中新增一个方法,那么就必须在接口各个实现类中实现这个接口,否则代码就会报错,但是在引入这种新的接口语法后,我们新增的接口中使用default修饰,那么只需要在需要的实现类中重新实现该方法即可,并不需要所有的接口中都要重新实现该接口方法.