Annotations & Generics in Java, java notes
Annotations & Generics in Java, java notes
o @Override
o @SuppressWarnings
o @Deprecated
o @Target
o @Retention
o @Inherited
o @Documented
@Override
@Override annotation assures that the subclass method is overriding the
parent class method. If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it
is better to mark @Override annotation that provides assurity that method
is overridden.
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler
prints warning. It informs user that it may be removed in the future
versions. So, it is better not to use such methods.
Example of custom annotation: creating, applying and
accessing annotation
//Creating annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation{
int value();
//Applying annotation
class Hello{
@MyAnnotation(value=10)
//Accessing annotation
class TestCustomAnnotation1{
Method m=h.getClass().getMethod("sayHello");
MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
}}
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with
type-safe objects. It makes the code stable by detecting the bugs at
compile time.
Before generics, we can store any type of objects in the collection, i.e.,
non-generic. Now generics force the java programmer to store a specific
type of objects.
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Generic Method
Like the generic class, we can create a generic method that can accept
any type of arguments. Here, the scope of arguments is limited to the
method where it is declared. It allows static as well as non-static methods.