Java Reference
In-Depth Information
Chapter 1
Annotations
In this chapter, you will learn
•
What annotations are
•
How to declare annotations
•
How to use annotations
•
What meta-annotations are and how to use them
•
Commonly used annotations
•
How to access annotations at runtime
•
How to process annotations in source code
What Are Annotations?
Annotations were introduced in Java 5. Before I define annotations and discuss their importance in programming,
let's discuss a simple example. Suppose you have an
Employee
class, which has a method called
setSalary()
that sets
the salary of an employee. The method accepts a parameter of the type
double
. The following snippet of code shows a
trivial implementation for the
Employee
class:
public class Employee {
public void setSalary(double salary) {
System.out.println("Employee.setSalary():" + salary);
}
}
A
Manager
class inherits from the
Employee
class. You want to set the salary for managers differently. You decide
to override the
setSalary()
method in the
Manager
class. The code for the
Manager
class is as follows:
public class Manager extends Employee {
// Override setSalary() in the Employee class
public void setSalary(int salary) {
System.out.println("Manager.setSalary():" + salary);
}
}