A Brief Introduction to Annotations in Java
Posted By : Neha Yadav | 30-Oct-2018
They do not
There are built-in
Some
1. @Override
2. @Deprecated
3. @SupressWarnings
1. @Override:- This annotation is used for the indication that a child class is overriding the method of the parent class. This
class A{
void show(){
System.out.println("Class A");
}
}
class B extends A{
@Override
void show(){
System.out.println("Class B");}
}
2. @Deprecated:- This annotation is used for the indication that a certain method, class etc will no longer be used in the java higher versions.
class A{
@Deprecated
void show(){
System.out.println("Class A");
}
}
3. @SupressWarnings:- This annotation is used to
class A{
@Deprecated
static void show(){
System.out.println("Class A");
}
}
class B{
@SupressWarnings("deprecation")
void show1(){
A.show();}
}
We can also create custom annotations according to our requirement. For
1. @Interface:- This annotation is used to create
Example:-
public @Interface HelloAnno{
String name() default "oodles";
}
usage:
@HelloAnno
public class ABC{
//...body
}
2. @Documented: This
Example:-
@Documented
public @Interface HelloAnno{
String name() default "oodles";
}
usage:
@HelloAnno
public class ABC{
//...body
}
3.
Example:-
@Target({ElementType.METHOD})
@Documented
public @Interface HelloAnno{
String name() default "oodles";
}
usage:
public class ABC{
//...body
@HelloAnno
void show(){
System.out.println("class ABC");
}
}
An annotation can have following possible Target values:-
ElementType.METHOD
ElementType.PACKAGE
ElementType.PARAMETER
ElementType.TYPE
ElementType.ANNOTATION_TYPE
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.FIELD
4. @Inherited:- This annotation indicated that custom annotation used on the parent will be applicable on the child classes.
Example:-
@Inherited
public @interface @HelloAnno {
}
@HelloAnno
public class ABC {
//body...
}
public class XYZ extends ABC {
//body ...
}
5. @Retention:- This
Example
@Retention(RetentionPolicy.RUNTIME)
@interface HelloAnno {
//body..
}
We can use different-different retention policies:-
RetentionPolicy.RUNTIME: Annotation applicable for runtime only.
RetentionPolicy.CLASS: Annotation applicable for .class only.
RetentionPolicy.SOURCE
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Neha Yadav
Neha is a creative person. She is having good knowledge of core java, advance java, hibernate,spring boot. She likes to solve puzzles, sudoku. She is a fun loving person.