Java Reference
In-Depth Information
Note that there is a mistake in the above code for 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 d
ouble
, 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's 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
^
1 error
The use of the
@Override
annotation did the trick. The
@Override
annotation is used with a non-static method
to indicate the programmer's intention to override the method in the superclass. At source code level, it serves the
purpose of documentation. When the compiler comes across the
@Override
annotation, it makes sure that the
method really overrides the method in the superclass. If the method annotated does not override a method in the
superclass, the compiler generates an error. In your case, the
setSalary(int salary)
method in the
Manager
class
does not override any method in the superclass
Employee
. This is the reason that you got the error. You may realize
that using an annotation is as simple as documenting the source code. However, they have compiler support. You can
use them to instruct the compiler to enforce some rules. Annotations provide benefits much more than you have seen
in this example.