Java用相同的方法在一個類中實現兩個接口哪種接口方法被覆蓋?
如果一個類型實現兩個接口,并且每個接口interface定義一個具有相同簽名的方法,則實際上只有一個方法,并且它們是不可區分的。例如,如果這兩個方法的返回類型沖突,那么它將是編譯錯誤。這是繼承,方法重寫,隱藏和聲明的一般規則,并且不僅適用于兩個繼承的interface方法之間的可能沖突,還適用于an interface和super class方法之間的沖突,甚至僅適用于泛型類型擦除引起的沖突。
相容性范例在下面的示例中,你有一個interface Gift具有present()方法(例如,贈送禮物)的和interface Guest,還具有一種present()方法(例如,客人在場并且不在場)。
Presentable johnny既是Gift和Guest。
public class InterfaceTest { interface Gift { void present(); } interface Guest { void present(); } interface Presentable extends Gift, Guest { } public static void main(String[] args) {Presentable johnny = new Presentable() { @Override public void present() {System.out.println('Heeeereee’s Johnny!!!'); }};johnny.present(); // 'Heeeereee’s Johnny!!!'((Gift) johnny).present(); // 'Heeeereee’s Johnny!!!'((Guest) johnny).present(); // 'Heeeereee’s Johnny!!!'Gift johnnyAsgift = (Gift) johnny;johnnyAsgift.present(); // 'Heeeereee’s Johnny!!!'Guest johnnyAsGuest = (Guest) johnny;johnnyAsGuest.present(); // 'Heeeereee’s Johnny!!!' }}
上面的代碼片段將編譯并運行。
請注意,只有一個 @Override 必要條件!!!。這是因為Gift.present()和Guest.present()是“- @Override等效的”(JLS 8.4.2)。
因此,johnny只有一個執行的present(),并不要緊,你如何對待johnny,無論是作為Gift或作為Guest,只有一個調用方法。
不兼容示例這是兩個不@Override等效的繼承方法的示例:
public class InterfaceTest { interface Gift { void present(); } interface Guest { boolean present(); } interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!! // 'types InterfaceTest.Guest and InterfaceTest.Gift are incompatible; // both define present(), but with unrelated return types'}
這進一步重申,從interface必須繼承成員必須遵守成員聲明的一般規則。下面我們就Gift和Guest定義present()不兼容的返回類型:一個void其他的boolean。由于不能同時使用an void present()和boolean present()in的原因,此示例導致編譯錯誤。
摘要你可以繼承@Override-equivalent的方法,但要遵循方法重寫和隱藏的通常要求。由于它們是 @Override等效的,因此實際上只有一種方法可以實現,因此沒有區別/選擇的地方。
編譯器不必標識哪個方法用于哪個接口,因為一旦確定@Override它們等效,它們就是相同的方法。
解決潛在的不兼容性可能是一項艱巨的任務,但這是另一個問題。
解決方法具有相同方法名稱和簽名的兩個接口。但是由單個類實現,那么編譯器將如何確定哪個方法用于哪個接口?
例如:
interface A{ int f();}interface B{ int f();}class Test implements A,B{ public static void main(String... args) throws Exception{ } @Override public int f() { // from which interface A or B return 0; }}
相關文章:
1. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處2. 圖片鏈接的地址怎么獲得的3. python - 我在使用pip install -r requirements.txt下載時,為什么部分能下載,部分不能下載4. mysql - 如何減少使用或者不用LEFT JOIN查詢?5. mysql - jdbc的問題6. mysql - eclispe無法打開數據庫連接7. mysql 5個left關鍵 然后再用搜索條件 幾千條數據就會卡,如何解決呢8. 視頻文件不能播放,怎么辦?9. mysql - 千萬級數據的表,添加unique約束,insert會不會很慢?10. html5 - H5 audio 微信端 在IOS上不能播放音樂
