Annotations Conclusion
What Are Annotations?
Before I define annotations and discuss their importance in programming, letâs look at 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 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);
}
}
There is a mistake in the Manager class, when you attempt to override the setSalary() method. Youâll
correct the mistake shortly. You have used the int data type as the parameter type for the incorrectly
overridden method. It is time to set the salary for a manager. The following code is used to accomplish this:
Employee ken = new Manager();
int salary = 200;
ken.setSalary(salary);
Employee.setSalary():200.0
This snippet of code was expected to call the setSalary() method of the Manager class but the output
does not show the expected result. What went wrong in your code? The intention of defining the setSalary() method in the Manager
class was to override the setSalary() method of the Employee class, not to overload it. You made a mistake.
You used the type int as the parameter type in the setSalary() method, instead of the type double in the Manager class.
You put comments indicating your intention to override the method in the Manager class.
However, comments do not stop you from making logical mistakes. You might spend, as every programmer does, hours and hours debugging errors resulting from this kind of logical mistake.
Who can help you in such situations? Annotations might help you in a few situations like this.
Let us rewrite your Manager class using an annotation. You do not need to know anything about
annotations at this point. All you are going to do is add one word to your program.
The following code is the modified version of the Manager class:
public class Manager extends Employee {
@Override
public void setSalary(int salary) {
System.out.println("Manager.setSalary():" + salary);
}
}
All you have added is a @Override annotation to the Manager class and removed the âdumbâ comments.
Trying to compile the revised Manager class results in a compile-time error that points to the use of the
@Override annotation for the setSalary() method of the Manager class:
Manager.java:2: error: method does not override or implement a method from a supertype
@Override