Java中的冲突接口方法 [英] Conflicting interface methods in Java
本文介绍了Java中的冲突接口方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
接口实现中的方法名称冲突--Java
<如果我们需要实现两个接口,这两个接口都包含一个具有相同名称和参数但返回类型不同的方法,我们该怎么办?例如:
What do we do if we need to implement two interfaces both of which contain a method with the same name and parameters, but different return types? For example:
interface A {
public int foo();
}
interface B {
public double foo();
}
class C implements A, B {
public int foo() {...} // compilation error
}
有没有一种简单的方法可以解决这个问题?
Is there an easy way to overcome this issue?
推荐答案
最简单的解决方案是始终在A中返回 double
,因为它可以存储每个可能的 int
值。
The simplest solution is to always return double
in A as it can store every possible int
value.
如果你不是一个选项,你需要使用替代继承。
If you is not an option you need to use an alternative to inheritance.
class C {
public A getA();
public B getB();
}
C c = new C();
int a = c.getA().foo();
double b = c.getB().foo();
这篇关于Java中的冲突接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文