Search code examples
javainheritanceinterfacejls

Interfaces implicitly declaring public methods of Object class?


According to The Java Language Specification, Java SE 16 Edition (JLS) §9.2 Interface Members:

If an interface has no direct superinterface types, 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, return type r, and throws clause t declared in Object (§4.3.2), unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

Why does any top-level Interface “implicitly” declare the public methods of the Object class? What is the purpose of this design?


Solution

  • What is the purpose of this design?

    Because you want to be able to call all the Object methods ( toString, equals, hashCode, and such) on every object of any type.

    interface Foo {
      
    }
    
    Foo foo = ...;
    
    foo.equals(otherFoo);
    

    Doesn't matter if I actually declared the equals method in the interface.