如果一个类型实现了两个接口,并且每个接口定义了一个签名相同的方法,那么实际上只有一个方法,它们是不可区分的。比如说,如果这两个方法的返回类型有冲突,那么这将是一个编译错误。这是继承、方法覆盖、隐藏和声明的一般规则,不仅适用于两个继承的接口方法之间可能发生的冲突,还适用于接口和超类方法之间的冲突,甚至只是由于泛型的类型擦除引起的冲突.
兼容性示例
这是一个例子,你有一个接口 Gift,它有一个 present() 方法(如赠送礼物),还有一个接口 Guest,它也有一个 present() 方法(如客人在场并且不缺席)。
显赫的约翰尼既是礼物也是客人。
public class InterfaceTest {
interface Gift { void present(); }
interface Guest { void present(); }
interface Presentable extends Gift, Guest { }
public static void main(String[] args) {
Presentable johnny = new Presentable() {
@Override public void present() {
System.out.println("Heeeereee's Johnny!!!");
}
};
johnny.present(); // "Heeeereee's Johnny!!!"
((Gift) johnny).present(); // "Heeeereee's Johnny!!!"
((Guest) johnny).present(); // "Heeeereee's Johnny!!!"
Gift johnnyAsGift = (Gift) johnny;
johnnyAsGift.present(); // "Heeeereee's Johnny!!!"
Guest johnnyAsGuest = (Guest) johnny;
johnnyAsGuest.present(); // "Heeeereee's Johnny!!!"
}
}
上面的sn-p编译运行。
请注意,只有一个@Override 是必需的!!!。这是因为 Gift.present() 和 Guest.present() 是“@Override-equivalent”(JLS 8.4.2)。
因此,johnny 只有一种 present() 实现,无论您如何对待 johnny,无论是作为礼物还是作为客人,都只有一种方法可以调用。
不兼容示例
这是一个示例,其中两个继承的方法不是 @Override 等效的:
public class InterfaceTest {
interface Gift { void present(); }
interface Guest { boolean present(); }
interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
// "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
// both define present(), but with unrelated return types"
}
这进一步重申了从接口继承成员必须遵守成员声明的一般规则。在这里,我们让 Gift 和 Guest 定义了带有不兼容返回类型的 present():一个是 void,另一个是布尔值。出于同样的原因,您不能在一种类型中使用 void present() 和 boolean present(),此示例会导致编译错误。
总结
您可以继承与@Override 等效的方法,但要遵守方法覆盖和隐藏的通常要求。由于它们是 @Override 等效的,因此实际上只有一种方法可以实现,因此没有什么可区分/选择的。
编译器不必确定哪个方法适用于哪个接口,因为一旦确定它们是@Override 等效的,它们就是同一个方法。
解决潜在的不兼容性可能是一项棘手的任务,但这完全是另一个问题。
参考文献
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8.4