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

§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

输出可能因系统而异

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值