Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Annotation is an interface then how it can extend an Object class?

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.

like image 478
Aamir Avatar asked Mar 17 '14 19:03

Aamir


People also ask

Can interface extends object class?

Interfaces in java don't inherit from Object class. They don't have default parent like classes in java.

How can an interface extend a class?

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.

Can annotations be extended?

In Java SE 6, annotations cannot subclass one another, and an annotation is not allowed to extend/implement any interfaces.

How interfaces can be extended?

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.


1 Answers

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

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.

like image 132
Sotirios Delimanolis Avatar answered Nov 15 '22 14:11

Sotirios Delimanolis