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. css3 - 沒明白盒子的height隨width的變化這段css是怎樣實現的?2. java - 根據月份查詢多個表里的內容怎么實現好?3. python3.x - c++調用python34. javascript - 在 model里定義的 引用表模型時,model為undefined。5. php工具中的mysql還是5.1以下的,請問如何才能升級到5.1以上?6. css3 - 這個右下角折角用css怎么畫出來?7. atom開始輸入!然后按tab只有空格出現沒有html格式出現8. javascript - 移動端自適應9. android - 課程表點擊后浮動后邊透明可以左右滑動的界面是什么?10. apache - 想把之前寫的單機版 windows 軟件改成網絡版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設服務器呢?
