第17条:要么为继承而设计,并提供文档说明,要么就禁止继承
第18条:接口优于抽象类
这两条中,提到了一个很重要的概念骨架实现。也就是说,抽象类实现接口的形式。这样的好处是,接口本来不能提供默认的实现,现在可以在抽象类中实现一些关键的方法。结合了接口和抽象类的优点。例如AbstractCollection,就是一个骨架实现。
另外,在查看源码的过程中,发现居然接口中也可以有方法体了。查了一下,原来是java8的新特性,用default关键字。
public interface Collection<E> extends Iterable<E> {
//省略其他代码
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
}