In my (probably naive) view, there was no need to violate interfaces like this. Interfaces have always been a contract you must fulfill, and this is a very simple and pure concept. Now it is a mix of several things. In my opinion:
- static methods do not belong to interfaces. They belong to utility classes.
- "default" methods shouldn't have been allowed in interfaces at all. You could always use an abstract class for this purpose.
In short:
Before Java 8:
- You could use abstract and regular classes to provide static and default methods. The role of interfaces is clear.
- All the methods in an interface should be overriden by implementing classes.
- You can't add a new method in an interface without modifying all the implementations, but this is actually a good thing.
After Java 8:
- There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.
- When programming the implementations, programmers may forget to override the default methods.
- There is a compilation error if a class tries to implement two or more interfaces having a default method with the same signature.
- By adding a default method to an interface, every implementing class automatically inherits this behavior. Some of these classes might have not been designed with that new functionality in mind, and this can cause problems. For instance, if someone adds a new default method
default void foo()
to an interfaceIx
, then the classCx
implementingIx
and having a privatefoo
method with the same signature does not compile.
What are the main reasons for such major changes, and what new benefits (if any) do they add?
主要意思是,他反对这种做法,认为静态方法应该属于静态类,而不应该属于接口,而default方法也不应该在接口中,应该在抽象类中。
原因是:1.接口中放了静态方法和default方法之后接口的概念不够清晰,而且接口和抽象类除了继承问题外没有太大区别。
2.原来只要定义在接口中的方法都要事先,现在有了default方法后,程序员可以不用重写,那么程序员很可能忘掉这点。
3.原来,你如果想要使用接口中的一个方法,你不得不实现所有的方法,这是一个优点,因为明确了所有的方法都要怎么实现,而现在如果一个类实现了两个接口,而这两个接口中有同名的default方法,那么直接编译异常(事实是编译器不知道该用哪个实现)。
4.那么为什么java不引进多重继承,而是在接口中定义default方法和静态方法呢?
针对这个问题,有各种解答:
有人的观点:
1静态方法的归属,静态方法是不优雅和惰性的,他应该被遗弃。当你使用很多的静态方法在程序中,单元测试和重构都会很麻烦。
2.多重继承是不好的,举例(the classic diamond problem).
3.JAVA官方的例子:
4.
我觉得这个人用例子解释的很好:
当你有两个接口的实现类非常复杂,你需要一个抽象的类,这两个接口都有独特的地方,所以你需要把这两个抽象类转化成一坨静态方法,把变量改成参数。接口实现着需要调用静态方法,会有大量的引用在程序中,这个会非常的冗杂。
例子就是上面的代码。
5.有人引用JavaDocument解释: