InterviewSolution
| 1. |
Java Annotations |
||||||||||||||
|
Answer» Annotations in Java are a form syntactic metadata which are used to CONVEY additional information about a program’s ELEMENTS like constructors, methods, instance variables and classes. They always start with @ symbol. Annotations have no direct effect in the compilation of the program. On the other side, annotations do not completely act like comments as they can transform the compiler’s perspective about the program. Let us see an example where annotations effect the output of a program. We are trying to override a private method . This will generate an error. class Parent { private void display() { System.out.println("Super class"); } } public class Example extends Parent { //using the Override annotation @Override void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } }The output is as follows: $javac Example.java Example.java:11: error: method does not override or IMPLEMENT a method from a supertype @Override ^ Example.java:19: error: display() has private access in Parent obj.display(); ^ 2 errorsBasically, Annotations are divided into three categories
Marker Annotations: They are used to point out at declaration. These annotations do not have any parameters. For example: @ExampleAnnotation()@Override is an example of a marker annotation. Full Annotations: These annotations consist of multiple variables’ name,value, pairs. For example: @ExampleAnnotation(name=”Program”, value=”Java”)Single value Annotations: These annotations consist only a single member with a shorthand value. For example: @ExampleAnnotation(“running”)There are a few built-in/ primitive annotations in Java. 3 of the built-in annotations are INCLUDED in the java.lang package. They are as follows
4 of them are imported the java.lang.annotation class, namely:
|
|||||||||||||||