Skip to main content
The @Inherited meta-annotation in Java specifies that an annotation applied to a class is automatically inherited by its subclasses. By default, annotations in Java are not inherited. Applying @Inherited to a custom annotation definition alters this behavior, instructing the JVM’s reflection mechanism to traverse up the class hierarchy to locate the annotation if it is not explicitly present on the queried subclass.

Syntax and Declaration

To create an inherited annotation, apply java.lang.annotation.Inherited to the annotation declaration. Because inheritance resolution typically occurs dynamically, it is almost always paired with @Retention(RetentionPolicy.RUNTIME).

Technical Mechanics and Limitations

The behavior of @Inherited is strictly governed by the Java Language Specification and operates under specific constraints:
  1. Class-Level Restriction: @Inherited only affects annotations applied to class declarations (ElementType.TYPE). It has absolutely no effect if the annotation is applied to methods, fields, constructors, or local variables. Subclass methods do not inherit annotations from overridden superclass methods, regardless of the @Inherited meta-annotation.
  2. Class Extension vs. Interface Implementation: The inheritance mechanism strictly follows class extension (extends). It does not apply to interface implementation (implements).
    • If an interface is annotated with an @Inherited annotation, classes that implement that interface will not inherit the annotation.
    • If a sub-interface extends a super-interface annotated with an @Inherited annotation, the sub-interface will not inherit the annotation.
  3. Reflection Resolution: The inheritance is resolved at runtime via the java.lang.Class reflection API. When Class.getAnnotation(Class<A> annotationClass) is invoked:
    • The JVM first checks if the annotation is directly present on the target class.
    • If absent, and the annotation type is meta-annotated with @Inherited, the JVM queries the superclass.
    • This recursive traversal continues up the inheritance tree until the annotation is found or java.lang.Object is reached.

Behavior Visualization

The following code demonstrates the strict class-hierarchy resolution of @Inherited:
If you query these classes using the Reflection API, the results align with the inheritance rules:

Annotation Overriding

If a subclass explicitly declares the same annotation that it would otherwise inherit, the subclass’s explicit annotation shadows (overrides) the superclass’s annotation. The reflection API will return the annotation directly present on the subclass, halting the upward traversal of the class hierarchy.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More