<分区>
J. Bloch 在他为 Java 6
编写的 Effective Java 中提到了以下内容(第 17 项):
If you feel that you must allow inheritance from such a class, one reasonable approach is to ensure that the class never invokes any of its overridable methods and to document this fact. In other words, eliminate the class’s self-use of overridable methods entirely.
第 18 项:
If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance. The resulting classes are less powerful and more fragile than wrapper classes.
While interfaces are not permitted to contain method implementations, using interfaces to define types does not prevent you from providing implementation assistance to programmers.
现在在 Java 8
中,其默认方法的实现(使用接口(interface)中的其他方法)接口(interface)对于继承是危险的。
例如:
public inteface MyInterface{
public void compute(Object o);
public default void computeAll(List<Object> oo){
for(Object o: oo)
compute(o); //self-use
}
}
因此,根据 J. Bloch 的说法,当我们尝试实现接口(interface)时可能会引入一些问题,因为:
重写这样的方法(类似于 J.Bloch 提供的方法):
public class MyInterfaceCounter implements MyInterface{ private int count = 0; @Override public void compute(Object o) { count++; } @Override public void computeAll(List<Object> oo){ count += oo.size(); //Damn!! MyInterface.super.computeAll(oo); } }
客户端访问接口(interface)的内部,即他们必须了解默认实现。
在 Java 8 中如何处理它? Effective Java apply 中的规则是否仍然适用?
此外,我们不能将默认方法声明为 final
(就像我们可以为类做的那样,这将使自用对重写者来说不太危险)。