JDK 8 中的一项新功能允许您添加到现有接口,同时保持二进制兼容性。
语法就像
public interface SomeInterface() {
void existingInterface();
void newInterface() default SomeClass.defaultImplementation;
}
这样,对于所有现有的实现,SomeInterface
当他们升级到这个新版本时,他们不会突然出现编译错误newInterface()
。
虽然这很简洁,但是当您实现两个接口时会发生什么,这两个接口都添加了一个您没有实现的新默认方法?让我用一个例子来解释。
public interface Attendance {
boolean present() default DefaultAttendance.present;
}
public interface Timeline {
boolean present() default DefaultTimeline.present;
}
public class TimeTravelingStudent implements Attendance, Timeline {
}
// which code gets called?
new TimeTravelingStudent().present();
这是否已被定义为 JDK 8 的一部分?
我发现 Java 之神在这里谈论类似的事情http://cs.oswego.edu/pipermail/lambda-lib/2011-February/000068.html,但它是私人邮件列表的一部分,我不能直接问他们。
有关如何在 JDK 8 中使用默认值以及扩展 Collection 接口以支持 lambdas 的更多详细信息,请参阅此处: https ://oracleus.wingateweb.com/published/oracleus2011/sessions/25066/25066_Cho223662.pdf