Interfaces implicitly declaring public methods of Object class?

Viewed 136

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?

2 Answers

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.

Every class is implicitly a subclass of Object

See: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html for more

Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

Related