Introduction to Annotations: Annotations in Java are special markers that provide metadata or extra information about the code to the compiler or runtime environment. They do not directly change the way your code executes but can influence the way it is compiled or processed by other tools. Annotations can be used to convey additional instructions or information, making the code more understandable and manageable.
Understanding Annotations:
Annotations are prefixed with the @
symbol followed by the annotation name. They can be applied to classes, methods, variables, and other elements in your code.
Example of Annotation Usage:
Consider two classes A
and B
where B
extends A
. If both classes have a method called printClassName
, and you create an object of class B
, the method from B
will be executed, which is known as method overriding. Annotations can help ensure this behavior is clear and correct.
class A {
void printClassName() {
System.out.println("Inside A method");
}
}
class B extends A {
@Override
void printClassName() {
System.out.println("Inside B method");
}
}
public class BasicAnnotations {
public static void main(String[] args) {
B b = new B();
b.printClassName(); // Output: Inside B method
}
}
Key Built-in Annotations:
@Override
: Indicates that a method is intended to override a method in a superclass. This helps prevent errors, such as mistyping the method name.@Deprecated
: Marks a method, class, or field as deprecated, signaling that it should no longer be used and may be removed in future versions. The compiler generates a warning when this element is used.@SuppressWarnings
: Instructs the compiler to ignore specific warnings for a particular piece of code.@Retention
: Specifies how long the annotation should be retained. The retention policy can be SOURCE
, CLASS
, or RUNTIME
.@FunctionalInterface
: Indicates that an interface is a functional interface, meaning it contains exactly one abstract method and can be used with lambda expressions.Extra Knowledge:
Introduction to Custom Annotations: While Java provides several built-in annotations, you can create your own custom annotations to add specific metadata to your code. Custom annotations are useful for enforcing coding standards, simplifying code management, and enabling powerful processing at compile-time or runtime.
Creating a Custom Annotation:
To create a custom annotation, you use the @interface
keyword. Custom annotations can have elements, which are similar to methods but without implementation.