One of the annotations available with the addition of the metadata
facility in Java Version 5.0 (see Chapter
1: Java and Chapter
1 Java: Supplement), greatly reduces the chance of accidentally
overloading when you really want to override. The @Override
annotation tells the compiler that you intend to override a method
from a superclass. If you don't get the parameter list quite right
so that you're really overloading the method name, the compiler
emits a compile-time error. This annotation is used as follows
public
class Parent {
int i = 0;
void doSomething (int k) {
i = k;
}
}
class Child extends Parent {
@Override
void doSomething (long k) {
i = 2 * k;
}
} |
The metadata facility in Java 5.0 supports simple and complex annotation
types, which are closely related to Java interfaces.
Some annotation types define member methods and member variables
and require parameters when used. However, the @Override
annotation is just a marker
interface. It has no members, and thus accepts no parameters
when used, as shown above. It must appear on a line by itself and
indicates that the method name on the next line should override
a method from a superclass. If the method signature on the next
line isn't really an overriding signature, then the compiler complains
as follows
Parent.java:10:
method does not override a method from its superclass
@Override
^ 1 error
By using @Override
each time you intend to override a method from a superclass, you
are safe from accidentally overloading instead of overriding.
References & Web
Resources
- Calvin Austin, J2SE
5.0 in a Nutshell, Sun Developer Network, May 2004.
- Java
Programming Language - Enhancements for JDK 5
- Annotations
- Java Programming Language Guide for JDK 5.
Latest update: Oct. 20, 2004
|