其实这个主要是为了解决接口升级造成的不兼容的情况。比如原来的接口 A 就这么几个方法,但是我现在要在 A 上再新增一个方法,那么之前所有 A 的实现类全部都要更改。特别是在 Java 8 中增加了比如 Stream 这样的方法。
Java 8 中 Collection 增加了这个方法:
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
要注意的是这个 default
方法不包含在函数式接口的方法中。在 @FunctionalInterface
接⼝注释中有这样一段描述:
* Conceptually, a functional interface has exactly one abstract
* method. Since {@linkplain java.lang.reflect.Method#isDefault()
* default methods} have an implementation, they are not abstract. If
* an interface declares an abstract method overriding one of the
* public methods of {@code java.lang.Object}, that also does
* <em>not</em> count toward the interface's abstract method count
* since any implementation of the interface will have an
* implementation from {@code java.lang.Object} or elsewhere.
说白了就是函数式接口的方法不包含 Object
的方法和 default
方法。
default
方法要有方法体。
还有就是比如 类 A 同时实现了接口 B 和 接口 C,B 和 C 都有 default
方法 doSth()
,那么 A 必须要重写 doSth()
方法。