如
§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
输出可能因系统而异