Java用相同的方法在一個類中實現(xiàn)兩個接口哪種接口方法被覆蓋?
如果一個類型實現(xiàn)兩個接口,并且每個接口interface定義一個具有相同簽名的方法,則實際上只有一個方法,并且它們是不可區(qū)分的。例如,如果這兩個方法的返回類型沖突,那么它將是編譯錯誤。這是繼承,方法重寫,隱藏和聲明的一般規(guī)則,并且不僅適用于兩個繼承的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只有一個執(zhí)行的present(),并不要緊,你如何對待johnny,無論是作為Gift或作為Guest,只有一個調(diào)用方法。
不兼容示例這是兩個不@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必須繼承成員必須遵守成員聲明的一般規(guī)則。下面我們就Gift和Guest定義present()不兼容的返回類型:一個void其他的boolean。由于不能同時使用an void present()和boolean present()in的原因,此示例導致編譯錯誤。
摘要你可以繼承@Override-equivalent的方法,但要遵循方法重寫和隱藏的通常要求。由于它們是 @Override等效的,因此實際上只有一種方法可以實現(xiàn),因此沒有區(qū)別/選擇的地方。
編譯器不必標識哪個方法用于哪個接口,因為一旦確定@Override它們等效,它們就是相同的方法。
解決潛在的不兼容性可能是一項艱巨的任務,但這是另一個問題。
解決方法具有相同方法名稱和簽名的兩個接口。但是由單個類實現(xiàn),那么編譯器將如何確定哪個方法用于哪個接口?
例如:
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. javascript - 可以DIY的頁面是如何實現(xiàn)的?2. mysql - SQL問個基礎例子,書上的,我怎么看都看不懂..誰幫我解釋一下第2個為什么和第1個一樣?3. python - 請問matplotlib.pyplot.save的路徑如何更改4. mysql服務無法啟動1067錯誤,誰知道正確的解決方法?5. 數(shù)據(jù)庫 - mysql boolean型無法插入true6. python - Django問題 ’WSGIRequest’ object has no attribute ’user’7. javascript - ajax 圖片文件與文本框數(shù)據(jù)一起提交上傳處理8. python - Django前臺url未能正確訪問方法求助?9. 無法遠程連接mysql10. javascript - js 對中文進行MD5加密和python結(jié)果不一樣。
