Java多接口同名方法的冲突

原文地址:https://www.cnblogs.com/estrigriac/p/11257455.html 

问题:如果有两个接口,他们恰好声明了同名方法,而这两个方法的参数相同,但返回类型不同。如何写一个类,同时实现这两个接口?

答:没法实现。这篇文章[1]已经给出证明了,就不再累述。

关于如何绕开这个问题,大致有两种方案。

一是声明一个同时实现两个返回类型的类[2][3],二是使用两个inner class分别继续这两个接口[4]。个人感觉区别不大,看情况使用即可。但第一个方案在处理继承多个类时行不通,而且处理void也很麻烦。

C#就很好地解决了这个问题。C#允许一个类在实现接口时,显式地标注实现的是哪个接口的哪个方法[5]。

参考资料

  1. https://www.geeksforgeeks.org/two-interfaces-methods-signature-different-return-types/
  2. https://stackoverflow.com/questions/31562741/two-interface-have-same-method-name-with-different-return-type
  3. https://coderanch.com/t/402880/java/methods-signature-return-types-interfaces
  4. https://stackoverflow.com/questions/31562741/two-interface-have-same-method-name-with-different-return-type
  5. https://www.geeksforgeeks.org/c-sharp-how-to-implement-multiple-interfaces-having-same-method-name/
posted @ 2019-07-28 01:04  banxiangzideren  阅读(2873)  评论(0编辑  收藏  举报