A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王俊杰 中级黑马   /  2013-3-4 21:06  /  1287 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这个问题由来已久。感觉有必要在这里讨论一下。
  1. interface InterfaceA {
  2.     int X();
  3. }
复制代码
  1. interface InterfaceB {
  2.     void X();
  3. }
复制代码
现在有一个类要同时实现这两个接口,但是这两个接口的方法仅仅是返回值不同
  1. class Test implements InterfaceA, InterfaceB {
  2.     //...
  3. }
复制代码
经测试没有办法实现X().

3 个回复

倒序浏览
哥们,你这么实现接口,那么这个类中就会出现名字相同,参数也相同的两个函数了(重载和返回值类型没有任何关系);那么当去调用x();方法,系统就不知道到底调用那个有返回值的还是调用那个没有返回值的了!所以当然没办法实现了咯
回复 使用道具 举报
在要实现这两个接口中的类中定义两个内部类,分别实现这两个接口
回复 使用道具 举报
内部类就能满足需求  不过最好还是避免这种写法
Java自带的接口不会出现这种问题 自己定义的接口要注意
  1. interface InterfaceA
  2. {
  3.         int x();
  4. }

  5. interface InterfaceB
  6. {
  7.         void x();
  8. }

  9. public class Test implements InterfaceA
  10. {
  11.         public int x()
  12.         {
  13.                 System.out.println("InterfaceA----");
  14.                 return 0;
  15.         }

  16.         private class TestIn implements InterfaceB    //内部类
  17.         {
  18.                 public void x()
  19.                 {
  20.                         System.out.println("InterfaceB----");
  21.                 }
  22.         }

  23.         public void xx()
  24.         {
  25.                 TestIn ti = new TestIn();
  26.                 ti.x();
  27.         }

  28.         public static void main(String[] args)
  29.         {
  30.                 Test t = new Test();
  31.                 t.x();
  32.                 t.xx();
  33.         }
  34. }
  35. //输出:InterfaceA----
  36. //         InterfaceB----
复制代码

评分

参与人数 1黑马币 +10 收起 理由
王俊杰 + 10 很给力!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马