java 继承两个接口,Java用相同的方法继承2个接口

In the following code snippets, first one does not compile, but second one does . Why? What is the difference?

1.

public class test {

static interface I1 { I1 m(); }

static interface I2 { I2 m(); }

static interface I12 extends I1,I2 {

public I12 m();

}

}

2.

public class test {

static interface I1 { I1 m(); }

static interface I2 { I2 m(); }

static class I12 implements I1,I2 {

public I12 m(){

return null;

}

}

}

解决方案

In Java 1.4 or earlier, both snippets should fail to compile. In 1.5 or later, both versions should compile.

If you override a method in Java 1.4, you must provide exactly the same return type as the base class method does.

This restriction was lifted in Java 1.5 and later, here you are allowed to provide a return type that inherits from the base class method's return type.

This makes sense, and can be useful. If you have:

I1 x = new I12Impl();

then all you know is x.m() returns an I1.

But if you have a bit more information:

I12 x = new I12Impl();

then you know that x.m() returns an I12 (which is also an I1).

This can be handy at times (for example, you might be able to avoid a downcast when calling x.m())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值