那么equals方法从何而来,接口是否也扩展了超类Object?如果是这样,接口如何扩展一个类?
Java 语言规范明确地处理了这个问题。
从第 9.2 节:
If an interface has no direct superinterfaces, 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, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
Basically, this is so that you can use equals
, hashCode
etc - because the way that the Java language is specified means that any concrete implementation of the interface will be a class, and that class must ultimately be a subclass of Object
, so the members will definitely be present.
To put it another way, while the interface itself doesn't extend Object
, it is known that any implementation will.
Here the class A no need to implements the method toString() as it's present in Object class. Then what is the objective of defining those method in collection interface as they can't force there implementation class to implement those method.
Usually this is just done for clarity, e.g. to document what is expected of an implementation in terms of the members declared in Object
.