黑马程序员技术交流社区
标题:
关于java接口的问题
[打印本页]
作者:
王俊杰
时间:
2013-3-4 21:06
标题:
关于java接口的问题
这个问题由来已久。感觉有必要在这里讨论一下。
interface InterfaceA {
int X();
}
复制代码
interface InterfaceB {
void X();
}
复制代码
现在有一个类要同时实现这两个接口,但是这两个接口的方法仅仅是返回值不同
class Test implements InterfaceA, InterfaceB {
//...
}
复制代码
经测试没有办法实现X().
作者:
罗威
时间:
2013-3-4 21:23
哥们,你这么实现接口,那么这个类中就会出现名字相同,参数也相同的两个函数了(重载和返回值类型没有任何关系);那么当去调用x();方法,系统就不知道到底调用那个有返回值的还是调用那个没有返回值的了!所以当然没办法实现了咯
作者:
牛合超
时间:
2013-3-4 21:24
在要实现这两个接口中的类中定义两个内部类,分别实现这两个接口
作者:
肖明凯
时间:
2013-3-4 21:30
内部类就能满足需求 不过最好还是避免这种写法
Java自带的接口不会出现这种问题 自己定义的接口要注意
interface InterfaceA
{
int x();
}
interface InterfaceB
{
void x();
}
public class Test implements InterfaceA
{
public int x()
{
System.out.println("InterfaceA----");
return 0;
}
private class TestIn implements InterfaceB //内部类
{
public void x()
{
System.out.println("InterfaceB----");
}
}
public void xx()
{
TestIn ti = new TestIn();
ti.x();
}
public static void main(String[] args)
{
Test t = new Test();
t.x();
t.xx();
}
}
//输出:InterfaceA----
// InterfaceB----
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2