user2820072 user2820072 - 2 months ago 6
Java Question

Does Interface java.util.Map overrides hashCode() and equals() from Object class

As per the Java-Doc for java.util.Map, the

hashCode
and
equals
methods are overridden from the
Object
class. But interfaces do not inherit from the
Object
class, so how does the
Map
interface override the
Object
class' methods?

Answer

The @Override annotation has special consideration for methods inherited from Object:

Quoting Java Language Specification, ยง9.6.4.4 @Override:

If a method declaration is annotated with the annotation @Override, but the method does not override or implement a method declared in a supertype, or is not override-equivalent to a public method of Object, a compile-time error occurs.

This means that @Override can annotate interface methods that will be inherited from Object in the implementing class, even though the interface itself is not inheriting from Object.

It is used as a safeguard against accidentally declaring an interface method that clashes with Object methods.

Comments