Java用相同的方法继承2个接口 [英] Java inherit 2 interfaces with the same method

查看:141
本文介绍了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;
           }
    }
}

推荐答案

在Java 1.4或更早版本中,两个代码片段都将无法编译.在1.5或更高版本中,两个版本均应编译.

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

如果您覆盖Java 1.4中的方法,则必须提供与基类方法完全相同的返回类型.

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

在Java 1.5和更高版本中取消了此限制,在这里您可以提供从基类方法的返回类型继承的返回类型.

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();

那么您所知道的就是x.m()返回一个I1.

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

但是,如果您还有更多信息:

But if you have a bit more information:

I12 x = new I12Impl();

然后您知道x.m()返回一个I12(也是I1).

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

这有时会很方便(例如,您可以在调用x.m()时避免沮丧)

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

这篇关于Java用相同的方法继承2个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆