更新時間:2019-08-12 17:49:14 來源:動力節點 瀏覽2404次
先從Java 8之前說起。要區分“聲明多繼承”與“實現多繼承”。
Java是不允許“實現多繼承”,簡稱不允許“多繼承”。但是Java支持“聲明多繼承”——Java的接口的多繼承——一個類可以實現多個接口(“繼承”了多個接口上的方法聲明),而一個接口可以繼承多個接口(同樣是“繼承”了多個接口上的方法聲明)。
接口只允許有方法聲明而不允許有實現,因而不會出現像C++那樣的實現多繼承的決議問題;抽象類可以有方法實現,但要遵循Java類的單繼承限制,也避免了實現多繼承的問題。這是早期Java為了與C++區分開的一個決定。
至于早期Java為何要做這樣的設計取舍,不必猜測,看看高司令老人家自己是怎么說的:
James Gosling on Java, May 1999
Bill Venners:In Java you included multiple inheritance of interface, but left out multiple inheritance of implementation. Were you trying to say anything to designers by making the interface a separate construct? Were you trying to say anything by leaving out multiple inheritance of implementation? How did that come about?
James Gosling: It listened to people from the C++ and Objective-C camps, and I tried to sort out who had the most happy experiences. The Objective-C notion of a pure interface with no implementation seemed to have worked out really well for people. It avoids a lot of the sticky issues such as disambiguation that people get into in C++. It's still kind of messy. It's an area that I don't feel totally happy with.
Bill Venners: In what way?
James Gosling: Another way for doing these things is a technique called delegation. Some ideas in the delegation camp felt good, but I never came up with anything that really worked. I ended up with the interface construct, which felt simple enough to be comprehensible, sophisticated enough to be useful. It also avoided any of the tar pits that the other folks got into.
純粹是高司令老人家的taste。
然后,從Java 8開始,接口允許為方法提供“默認實現”了——默認方法(default method)。因而實質上Java 8的接口多繼承其實也會涉及到實現多繼承,并且語言層面有專門規定去解決實現多繼承時選擇哪個版本的問題——哪個都不選擇,而是在發現會繼承多個默認方法實現并且沒有override時報錯,逼使用戶顯式override可能沖突的方法。
這使得Java 8開始接口可以當作traits來使用,達到實現多繼承的目的。
Java 8語言規范的一些相關新規定:
8.4.8. Inheritance, Overriding, and Hiding
9.4. Method Declarations
13.5.6. Interface Method Declarations
以上就是動力節點java培訓班給大家做的內容詳解,更多關于java的學習,請繼續關注動力節點java學院官網。更多精彩等你來看。
相關閱讀
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習