Java – why does the interface extend object according to the class file format?

Why does the JVM specification declare that the interface must have a super of Java / Lang / object_ Class, even if the interface does not extend Java / Lang / object?

I specifically refer to § 4.1 of the JVM specification, which says:

But in the JLS in 2007, it means that the interface does not extend object Instead, an implicitly created abstract method is declared, which matches each public method in the object class:

Solution

As described in § 9.2:

Therefore, we can see that although the interface without direct super interface does not explicitly extend object, it is still internally linked with the object class, because it is used by the compiler to insert abstract methods with the same signature and return type, as well as the public methods with throws clause in the object class and in the interface This is why for an interface, super_ The value of the class item must always be constant_ A valid index in the pool table Constant at this index_ The pool entry must be a constant representing the class object_ Class_ Info structure This is why interface reference variables can successfully call public instance methods, such as object's toString () method For example, consider the code given below:

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
    }
}

Even if the toString () method (method of object) is not declared in myinterface, the above code will compile successfully The above code provides the following output on my system:

InterfaceTest@1ba34f2

The output may vary from system to system

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>