JVM Specification Reading 1

今天讀JVM Specification的introduce部分,讀到這麼一句:
    JSR 335 also introduced private and static methods in interfaces at the class file level.
不可思議,接口中竟然可以定義方法了而且還可以定義靜態方法!爲什麼要這麼做?原來的abstract方法不是可以實現同樣的功能麼?爲什麼這麼做?
     In Java 8, interfaces can contain implemented methods, static methods, and the so-called "default" methods (which the implementing classes do not need to override).

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:

  1. static methods do not belong to interfaces. They belong to utility classes.
  2. "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 interface Ix, then the class Cx implementing Ix and having a private foo 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解釋:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章