原文地址:https://www.cnblogs.com/estrigriac/p/11257455.html
問題:如果有兩個接口,他們恰好聲明了同名方法,而這兩個方法的參數相同,但返回類型不同。如何寫一個類,同時實現這兩個接口?
答:沒法實現。這篇文章[1]已經給出證明了,就不再累述。
關於如何繞開這個問題,大致有兩種方案。
一是聲明一個同時實現兩個返回類型的類[2][3],二是使用兩個inner class分別繼續這兩個接口[4]。個人感覺區別不大,看情況使用即可。但第一個方案在處理繼承多個類時行不通,而且處理void也很麻煩。
C#就很好地解決了這個問題。C#允許一個類在實現接口時,顯式地標注實現的是哪個接口的哪個方法[5]。
參考資料
- https://www.geeksforgeeks.org/two-interfaces-methods-signature-different-return-types/
- https://stackoverflow.com/questions/31562741/two-interface-have-same-method-name-with-different-return-type
- https://coderanch.com/t/402880/java/methods-signature-return-types-interfaces
- https://stackoverflow.com/questions/31562741/two-interface-have-same-method-name-with-different-return-type
- https://www.geeksforgeeks.org/c-sharp-how-to-implement-multiple-interfaces-having-same-method-name/
