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 errors

Basically, Annotations are divided into three categories

  1. Marker Annotations
  2. Full Annotations
  3. Single value Annotations

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

  • @Deprecated
  •  @Override
  • @SuppressWarnings

4 of them are imported the java.lang.annotation class, namely:

  • @Retention
  • @Documented
  • @Inherited
  • @Target
Annotation
Description
@Deprecated
A marker annotation that INDICATES that the declaration is outdated and has been updated
@Override
A marker annotation used when a method overrides another method from a parent class
@SuppressWarnings
It is used to generate compiler warnings
@Documented
It is a marker annotation that  tells a tool that an annotation is to be documented
@Inherited
It is used only on declaration of an annotation
@Target
It acts as an annotation to another annotation


Discussion

No Comment Found