Chapter: Java Annotations


1. Basics of Java Annotations

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:

Extra Knowledge:


2. Custom Annotations

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.