加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么接口根据类文件格式扩展Object?

发布时间:2020-12-14 05:27:25 所属栏目:Java 来源:网络整理
导读:为什么JVM规范声明接口必须具有 java / lang / Object的super_class,即使接口不扩展java / lang / Object? 我具体指的是JVM规范的§4.1,它说: For an interface,the value of the super_class item must always be a valid index into the constant_pool t
为什么JVM规范声明接口必须具有 java / lang / Object的super_class,即使接口不扩展java / lang / Object?

我具体指的是JVM规范的§4.1,它说:

For an interface,the value of the super_class item must always be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Class_info structure representing the class Object.

但在07年的JLS中,它表示接口不扩展Object.相反,声明了一个隐式创建的抽象方法,它匹配Object类中的每个公共方法:

If an interface has no direct superinterfaces,then the interface implicitly declares a public abstract member method m with signature s,return type r,and throws clause t corresponding to each public instance method m with signature s,and throws clause t declared in Object,unless a method with the same signature,same return type,and a compatible throws clause is explicitly declared by the interface.

解决方法

如 §9.2所述:

If an interface has no direct superinterfaces,then the interface
implicitly declares a public abstract member method m with signature
s,and throws clause t corresponding to each public
instance method m with signature s,and throws clause t
declared in Object,same
return type,and a compatible throws clause is explicitly declared by
the interface.

因此,我们看到,虽然没有直接超级接口的接口没有显式地扩展Object,但是它仍然在内部与Object类有链接,因为它被编译器用来插入具有相同签名和返回类型的抽象方法以及throws子句在Object类中,在接口内的公共方法.这就是为什么对于一个接口,super_class项的值必须始终是constant_pool表中的有效索引.该索引处的constant_pool条目必须是表示类Object的CONSTANT_Class_info结构.这就是为什么接口参考变量可以成功地调用公共实例方法,例如Object的toString()方法.例如,考虑下面给出的代码:

interface MyInterface
{}
public class InterfaceTest implements MyInterface
{
    public static void main(String[] args) 
    {
        MyInterface mInterface = new InterfaceTest();
        System.out.println(mInterface.toString());//Compiles successfully. Although toString() is not declared within MyInterface
    }
}

即使在MyInterface中未声明toString()方法(Object的方法)),上述代码也会成功编译.以上代码在我的系统上提供以下输出:

InterfaceTest@1ba34f2

输出可能因系统而异

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读