更新時間:2019-08-12 17:49:14 來源:動力節(jié)點 瀏覽2634次
先從Java 8之前說起。要區(qū)分“聲明多繼承”與“實現(xiàn)多繼承”。
Java是不允許“實現(xiàn)多繼承”,簡稱不允許“多繼承”。但是Java支持“聲明多繼承”——Java的接口的多繼承——一個類可以實現(xiàn)多個接口(“繼承”了多個接口上的方法聲明),而一個接口可以繼承多個接口(同樣是“繼承”了多個接口上的方法聲明)。
接口只允許有方法聲明而不允許有實現(xiàn),因而不會出現(xiàn)像C++那樣的實現(xiàn)多繼承的決議問題;抽象類可以有方法實現(xiàn),但要遵循Java類的單繼承限制,也避免了實現(xiàn)多繼承的問題。這是早期Java為了與C++區(qū)分開的一個決定。
至于早期Java為何要做這樣的設(shè)計取舍,不必猜測,看看高司令老人家自己是怎么說的:
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開始,接口允許為方法提供“默認(rèn)實現(xiàn)”了——默認(rèn)方法(default method)。因而實質(zhì)上Java 8的接口多繼承其實也會涉及到實現(xiàn)多繼承,并且語言層面有專門規(guī)定去解決實現(xiàn)多繼承時選擇哪個版本的問題——哪個都不選擇,而是在發(fā)現(xiàn)會繼承多個默認(rèn)方法實現(xiàn)并且沒有override時報錯,逼使用戶顯式override可能沖突的方法。
這使得Java 8開始接口可以當(dāng)作traits來使用,達(dá)到實現(xiàn)多繼承的目的。
Java 8語言規(guī)范的一些相關(guān)新規(guī)定:
8.4.8. Inheritance, Overriding, and Hiding
9.4. Method Declarations
13.5.6. Interface Method Declarations
以上就是動力節(jié)點java培訓(xùn)班給大家做的內(nèi)容詳解,更多關(guān)于java的學(xué)習(xí),請繼續(xù)關(guān)注動力節(jié)點java學(xué)院官網(wǎng)。更多精彩等你來看。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743