6

Herbert Schildt mentions in his book on Java,

@Inherited is a marker annotation that can be used only on another annotation declaration. Furthermore, it affects only annotations that will be used on class declarations. @Inherited causes the annotation for a superclass to be inherited by a subclass.

Therefore, when a request for a specific annotation is made to the subclass, if that annotation is not present in the subclass, then its superclass is checked. If that annotation is present in the superclass, and if it is annotated with @Inherited, then that annotation will be returned.

I know pretty well that annotations are not inherited. Exceptions are annotations, which its declaration is annotated with @Inherited.

I have understood the rest of the annotations which includes java.lang.annotation: @Retention, @Documented, and @Target. and other three—@Override, @Deprecated, and @SuppressWarnings.

I am a bit confused when it comes to the @Inherited annotation. Could someone demonstrate it with a simple foobar example?

Secondly, going through one of the questions regarding this on StackOverflow, I came across this,

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited public @interface Baz { String value(); } public interface Foo{ @Baz("baz") void doStuff(); } public interface Bar{ @Baz("phleem") void doStuff(); } public class Flipp{ @Baz("flopp") public void doStuff(){} } 

What use does the @Inherited annotation have when put on the annotation @interface Baz?

Please don't explain me in context with annotations used Spring Framework, I am no in way familiar with it.

0

1 Answer 1

12

First, as the quote you posted states,

it affects only annotations that will be used on class declarations

So your example doesn't apply since you're annotating methods.

Here's one that does.

public class Test { public static void main(String[] args) throws Exception { System.out.println(Bar.class.isAnnotationPresent(InheritedAnnotation.class)); } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) //@Inherited @interface InheritedAnnotation { } @InheritedAnnotation class Foo { } class Bar extends Foo { } 

This will print false since the CustomAnnotation is not annotated with @Inherited. If you uncomment the use of @Inherited, it will print true.

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

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.