search
HomeJavajavaTutorialJava @Inherited

The @inherited in Java is an annotation used to mark an annotation to be inherited to subclasses of the annotated class. The @inherited is a built-in annotation, as we know that annotations are like a tag that represents metadata which gives the additional information to the compiler. Same as built-in annotation, which is exits in the Javadoc, it is possible to create another meta-annotation out of existing in the java. There are actually two types of annotations, one type of annotations applied to the java code like @override, and another type of annotations applied to the other annotation like @target @inherited. So @inherited is an annotation that is applied to other annotation whose we want to create subclasses or we want to inherit to make another user define annotation.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

The syntax of the @inherited in java is –

@Inherited
public @interface MyAnnotation {// code of the MyAnnotation
}
@MyAnnotation
public class SuperClass {
// code of the SuperClass }
public class SubClass extends SuperClass { // code of the SubClass }

As in the above syntax, the class SubClass is inherited from the annotation @MyAnnotation, because it is inherited from SuperClass, and SuperClass has a @MyAnnotation annotation.

How does @Inherited work in Java?

The @Inherited annotation is used or annotated to the annotation (MyAnnotation as in above syntax), which the @interface should prefix. Next, this annotation (MyAnnotation) can be used where ever need to apply as @MyAnnotation. These annotations can be applied just before the declaration of an element and can be applied to any element of the program like variables, class, constructors, methods, etc. When this user-defined annotation is annotated on the superclass, it is automatically inherited to subclasses (subclass as in the above syntax), as we can see in the below examples.

Examples to Implement @Inherited annotation in Java

Next, we write the java code to understand the @Inherited annotation more clearly with the following example where we use @Inherited annotation to inherit in the subclass from the superclass, as below –

Example #1

First, we create an interface for annotation @MyAnnotation, which has two fields, name and code.

Code: //MyAnnotation.java

package demo;
import java.lang.annotation.Inherited;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Target ({ElementType.TYPE, ElementType.METHOD})
@Retention (RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
String name () default "unknown";
String code () default " ";
}

Next, we create a superclass to use the above annotation by annotating any class or method or variable and provide the state name and state code.

Code: //Super.java

package demo;
import demo.MyAnnotation;
@MyAnnotation (name = "Karnataka", code = "KA")
public class Super
{
public String getstateinfo ()
{
return null;
}
}

Next, we use an annotation because it is metadata, which means we should be able to get this metadata or information to use the annotation information when we need it.

Code: //Demo.java

//as sub class
package demo;
import demo.MyAnnotation;
import demo.Super;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
public class Demo extends Super
{
public static void main ( String[] arg ) throws Exception
{
new Super ();
Class <super>obj = Super.class;
getstateinfo (obj);
Method m = obj.getMethod ("getstateinfo", new Class[]{});
getstateinfo (m);
}
static void getstateinfo (AnnotatedElement e)
{
try
{
System.out.println ("Finding annotations on " + e.getClass ().getName ());
Annotation[] annotations = e.getAnnotations ();
for (Annotation a : annotations)
{
if (a instanceof MyAnnotation)
{
MyAnnotation stateInfo = (MyAnnotation) a;
System.out.println("Name of Annotation :" + stateInfo.annotationType ());
System.out.println("State Name :" + stateInfo.name ());
System.out.println("State code :" + stateInfo.code ());
System.out.println(new Demo ().getClass ().getAnnotation (MyAnnotation.class));
System.out.println(new Super ().getClass ().getAnnotation (MyAnnotation.class));
}
}
} catch (Exception ex)
{
System.out.println( ex );
}
}
}</super>

Output: When we run the Demo.java class, the output is.

Java @Inherited

Explanation: As in the above code, the MyAnnotation annotation is created an also annotated by @Inherited. In the Superclass, the MyAnnotation annotation was using by the statement @MyAnnotation and annotated to the class. And another class Demo is created, which is the subclass of the Superclass because it is extended to Superclass. Farther in the main () method of the Demo class, an object of the Superclass is creating and access its method that is getstateinfo (), through this methoditerating all its annotations and checking whether the annotation is inatnce of MyAnnotation, if yes then printing some of the information as we can see above. But one important thing is that the Demo class or any of its elements not annotated to the MyAnnotation, but it still showing that the MyAnnotation is annotated to this class because it is inherent to the Superclass and Superclass is inherited MyAnnotation.

Next, we rewrite the above java code to understand the @Inherited annotation more clearly with the following example where we will not use @Inherited annotation to annotation MyAnnotation (as annotation created in the above example) to check whether this annotation is inherited in the subclass from its superclass or not, as below –

Example #2

We will keep Super.java and the Demo.java classes the same as above no changes in those classes, but in MyAnnotation.java class, we do little change, just we remove the @Inherited annotation to annotate from the MyAnnotation, as we can see below –

Code: //MyAnnotation.java

package demo;
import java.lang.annotation.Inherited;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// no @Inherited
@Target ({ElementType.TYPE, ElementType.METHOD})
@Retention (RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
String name () default "unknown";
String code () default " ";
}

Output: Next, when we run the Demo.java class, the output is.

Java @Inherited

Explanation: As in the above output, we can see that after state code, the “null” value is printed, that is the return value of the statement “new  Demo ().getClass ().getAnnotation (MyAnnotation.class)”, which means that the demo class is not inherited (or annotated) any MyAnnotation annotation from it Superclass, because the @Inherited annotation is not annotated to MyAnnotation to inherit it in the subclass.

Conclusion

The @inherited in java is a built-in annotation applied to another annotation. It is used to marks an annotation to be inherited to subclasses of the annotated class. The @inherited is available in the package java.lang.annotation.Inherited.

The above is the detailed content of Java @Inherited. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.