Java用相同的方法在一个类中实现两个接口哪种接口方法被覆盖?

如何解决Java用相同的方法在一个类中实现两个接口哪种接口方法被覆盖??
如果一个类型实现两个接口,并且每个接口interface定义一个具有相同签名的方法,则实际上只有一个方法,并且它们是不可区分的。例如,如果这两个方法的返回类型冲突,那么它将是编译错误。这是继承,方法重写,隐藏和声明的一般规则,并且不仅适用于两个继承的interface方法之间的可能冲突,还适用于an interface和super class方法之间的冲突,甚至仅适用于泛型类型擦除引起的冲突。

相容性范例 在下面的示例中,你有一个interface Gift具有present()方法(例如,赠送礼物)的和interface Guest,还具有一种present()方法(例如,客人在场并且不在场)。

Presentable johnny既是Gift和Guest。

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!!!"
}
}
上面的代码片段将编译并运行。

请注意,只有一个 @Override 必要条件!!!。这是因为Gift.present()和Guest.present()是“- @Override等效的”(JLS 8.4.2)。

因此,johnny只有一个执行的present(),并不要紧,你如何对待johnny,无论是作为Gift或作为Guest,只有一个调用方法。

不兼容示例 这是两个不@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"
}
这进一步重申,从interface必须继承成员必须遵守成员声明的一般规则。下面我们就Gift和Guest定义present()不兼容的返回类型:一个void其他的boolean。由于不能同时使用an void present()和boolean present()in的原因,此示例导致编译错误。

摘要 你可以继承@Override-equivalent的方法,但要遵循方法重写和隐藏的通常要求。由于它们是 @Override等效的,因此实际上只有一种方法可以实现,因此没有区别/选择的地方。

编译器不必标识哪个方法用于哪个接口,因为一旦确定@Override它们等效,它们就是相同的方法。

解决潜在的不兼容性可能是一项艰巨的任务,但这是另一个问题。

解决方法
具有相同方法名称和签名的两个接口。但是由单个类实现,那么编译器将如何确定哪个方法用于哪个接口?

例如:

interface A{
int f();
}
interface B{
int f();
}
class Test implements A,B{
public static void main(String... args) throws Exception{
}
@Override
public int f() { // from which interface A or B
return 0;
}
}
声明:地推任务网所有作品(图片、文字)均由用户自行上传分享,仅供网友学习交流。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dituirenwu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值