All annotation types in Java automatically extend the Annotation interface. Thus, Annotation is a super interface of all annotations. It is declared within the java.lang.annotation package. It overrides hashCode( ),equals( ), and toString( ), which are defined by Object. But how come an Interface is able to override object methods. An interface must contain only abstract methods, atleast traditional interfaces. So is it supplying some form of implementation?
I visited the source code of The Annotation interface, but all the methods are only declared but not defined. So why overriden
Interface methods cannot "override" methods in a class. Interface methods can only override interface methods in its superinterfaces (see also JLS).
What is happening in java.lang.annotation.Annotation
, is that Annotation
just happens to declare toString
, hashCode
, and equals
in its interface body. You can do this when declaring your own interfaces too:
interface MyInterface {
String toString();
int hashCode();
boolean equals(Object other);
}
This is usually redundant, since all Object
s have these methods anyway. Presumably, Annotation
does this to "override" the documentation for these methods, to talk about the behaviour of these methods on an annotation. For example, the documentation for hashCode
describes exactly how a hash code for an annotation is generated.
When you actually get an instance of an annotation with getAnnotation
for example:
SomeAnnotation foo = SomeClass.class.getAnnotation(SomeAnnotation.class);
You can inspect foo.getClass()
and see that it is not SomeAnnotation
, but some proxy class (in Java 21 at least, probably subject to implementation details) implementing SomeAnnotation
. After all, you cannot create an instance of an interface.
While annotation interfaces don't override toString
, equals
and hashCode
, you could say that this proxy class returned by getAnnotation
does override them.