For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/
In this article, let us discuss the support for annotations in Java, from the Java 11 certification perspective.
What are annotations?
Annotations are metadata (data about data) assigned to classes, methods, variables etc. in Java.
Annotations start with the at ( @ ) symbol and can contain attribute/value pairs called elements.
For example, @Override annotation informs the compiler that the element is meant to override an element declared in a superclass.
@Override
void mySuperMethod() { ... }
How are annotations defined?
To define an annotation type, we use the keyword interface, preceded by the at sign (@) (@ = AT, as in annotation type).
In the below example, Fitness is defined as anĀ annotation type. This Fitness annotation is then applied to the Student class.
public @interface Fitness {
}
@Fitness public class Student extends Person {}
What is a marker annotation?
A marker annotation is an annotation that does not contain any elements. In the above example, Fitness is defined as a marker annotation, it has no elements.
How do we define an annotation with elements?
We can specify the annotation element declarations within the annotation type interface. These look a lot like methods and they can define optional default values.
For example, we can add two elements in the Fitness annotation as shown below.
public @interface Fitness {
int dailyHours();
String fitnessType() default "jogging";
}
@Fitness(dailyHours=5)
class Student {
}
Here, the annotation Fitness has two elements – dailyHours and fitnessType. When the Fitness annotation is applied to Student, it is optional to provide a value for fitnessType because it has a default value “jogging”. However, a value has to be provided for dailyHours element.
References
For more information on this topic, you can refer https://docs.oracle.com/javase/tutorial/java/annotations/declaring.html