0

I saw some code and I am trying to understand it. In the code below, an interface extends an annotation. I don't understand why it is possible. What's the point of having an interface extending an annotation? How to use an interface that extends an annotation? Thanks!

public interface TheScope extends javax.inject.Scope { ... } public ScopeClazz implements TheScope { ... } 
4
  • 1
    If ScopeClazz is a class, then this won't compile... Commented Jan 16, 2013 at 0:42
  • Sorry, there is a typo. It should be implements instead of extends. I modified the question. Commented Jan 16, 2013 at 0:46
  • Is TheScope your own interface? Commented Jan 16, 2013 at 0:52
  • Yes, it is defined by me. Commented Jan 16, 2013 at 0:52

3 Answers 3

1

According to the Java annotation types specification:

Unless explicitly modified herein, all of the rules that apply to ordinary interface declarations apply to annotation type declarations.

For example, annotation types share the same namespace as ordinary class and interface types; and annotation type declarations are legal wherever interface declarations are legal, and have the same scope and accessibility.

Therefore, you can implement annotation types just as you would interfaces. The only difference is you cannot extend an annotation with another annotation.

Sign up to request clarification or add additional context in comments.

Comments

0

javax.inject.Scope is also an Interface (what else?!) see http://docs.oracle.com/javaee/6/api/javax/inject/Scope.html

5 Comments

The java doc for it is here: docs.oracle.com/javaee/6/api/javax/inject/Scope.html. It is an annotation type.
Actually, the @ before the interface keyword marks it is an annotation. The examples confirm that.
if its called interface then its an interface, with or without annotation marker
... and where is it "called interface"? Don't you find it curious the title of the javadoc page is "Annotation Type Scope"?
in javadox line 4: public @interface Scope. An anotation is a special interface,see dicarlos answer
0

Aside from being usable as annotations, annotation types are ordinary interfaces. This is useful when reading annotations at runtime, because the annotation can then be represented as an instance of the annotation type.

As a side effect of this implementation choice, you can extend or implement them like any other interface. This is completely independent of using this type as annotation. Since this means the same type would be used for two different things (as annotation type and ordinary interface), such usage would likely violate separation of concerns, and is uncommon. However, from a language point of view, the semantics are clear and not dangerous, so there is little reason to require the compiler to prevent this corner case from occuring.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.