黑马程序员技术交流社区

标题: 关于java接口的问题 [打印本页]

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

作者: 罗威    时间: 2013-3-4 21:23
哥们,你这么实现接口,那么这个类中就会出现名字相同,参数也相同的两个函数了(重载和返回值类型没有任何关系);那么当去调用x();方法,系统就不知道到底调用那个有返回值的还是调用那个没有返回值的了!所以当然没办法实现了咯
作者: 牛合超    时间: 2013-3-4 21:24
在要实现这两个接口中的类中定义两个内部类,分别实现这两个接口
作者: 肖明凯    时间: 2013-3-4 21:30
内部类就能满足需求  不过最好还是避免这种写法
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----
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2