接口隐式声明对象 class 的 public 方法?

Interfaces implicitly declaring public methods of Object class?

根据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.

为什么任何顶级接口都“隐式”声明 Object class 的 public 方法?这样设计的目的是什么?

每个 class 都是 Object

的子class

参见:https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 了解更多

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.

What is the purpose of this design?

因为您希望能够在任何类型的每个对象上调用所有 Object methods ( toString, equals, hashCode,等等)。

interface Foo {
  
}

Foo foo = ...;

foo.equals(otherFoo);

我是否真的在接口中声明了 equals 方法并不重要。