We define an annotation as an interface as below
@interface annot_name {
}
and we know that all annotations extends interface java.lang.annotation.Annotation
by default.
When I checked the java library for Annotation
interface I found that it was overridding many methods of Object class like hashCode()
etc.
If Annotation is an interface then how could it extend an Object class and override its methods? Interfaces can only extends other interfaces and not classes.
Interfaces in java don't inherit from Object class. They don't have default parent like classes in java.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.
In Java SE 6, annotations cannot subclass one another, and an annotation is not allowed to extend/implement any interfaces.
An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
So my question is if Annotation is an interface then how could it extends an Object class and override its methods
Not exactly. The Java Language Specification §9.2 says
If an interface has no direct superinterfaces, then the interface implicitly declares a
public abstract
member methodm
with signatures
, return typer
, andthrows
clauset
corresponding to eachpublic
instance methodm
with signatures
, return typer
, andthrows
clauset
declared inObject
, unless a method with the same signature, same return type, and a compatiblethrows
clause is explicitly declared by the interface.
So any interface
gets those methods.
For Annotation
, the designers just chose to re-declare them in the source code so they could document their behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With