您的位置:首頁技術文章
文章詳情頁

Java用相同的方法在一個類中實現兩個接口哪種接口方法被覆蓋?

瀏覽:107日期:2024-05-07 18:11:26
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解決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; }}

標簽: java
相關文章:
国产综合久久一区二区三区