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

前端之家收集整理的这篇文章主要介绍了java – 为什么接口根据类文件格式扩展Object?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么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

输出可能因系统而异

猜你在找的Java相关文章