Java用相同的方法在一個類中實(shí)現(xiàn)兩個接口。哪種接口方法被覆蓋?
如果一個類型實(shí)現(xiàn)兩個接口,并且每個接口interface定義一個具有相同簽名的方法,則實(shí)際上只有一個方法,并且它們是不可區(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!!!' }}
上面的代碼片段將編譯并運(yùn)行。
請注意,只有一個 @Override 必要條件?。?!。這是因?yàn)镚ift.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'}
這進(jìn)一步重申,從interface必須繼承成員必須遵守成員聲明的一般規(guī)則。下面我們就Gift和Guest定義present()不兼容的返回類型:一個void其他的boolean。由于不能同時使用an void present()和boolean present()in的原因,此示例導(dǎo)致編譯錯誤。
摘要你可以繼承@Override-equivalent的方法,但要遵循方法重寫和隱藏的通常要求。由于它們是 @Override等效的,因此實(shí)際上只有一種方法可以實(shí)現(xiàn),因此沒有區(qū)別/選擇的地方。
編譯器不必標(biāo)識哪個方法用于哪個接口,因?yàn)橐坏┐_定@Override它們等效,它們就是相同的方法。
解決潛在的不兼容性可能是一項艱巨的任務(wù),但這是另一個問題。
解決方法具有相同方法名稱和簽名的兩個接口。但是由單個類實(shí)現(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; }}
相關(guān)文章:
1. javascript - 在 vue里面用import引入js文件,結(jié)果為undefined2. html - 爬蟲時出現(xiàn)“DNS lookup failed”,打開網(wǎng)頁卻沒問題,這是什么情況?3. 求教一個mysql建表分組索引問題4. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發(fā)現(xiàn)5. html5 - input type=’file’ 上傳獲取的fileList對象怎么存儲于瀏覽器?6. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?7. python沒入門,請教一個問題8. php如何獲取訪問者路由器的mac地址9. node.js - 用nodejs 的node-xlsx模塊去讀取excel中的數(shù)據(jù),可是讀取出來的日期是數(shù)字,請問該如何讀取日期呢?10. javascript - 我的站點(diǎn)貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?
